本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
重要
该 AWS OpsWorks Stacks 服务于 2024 年 5 月 26 日终止,新客户和现有客户均已禁用。我们强烈建议客户尽快将其工作负载迁移到其他解决方案。如果您对迁移有疑问,请通过 re AWS : Post 或通过 Pre
本主题介绍了 AWS OpsWorks Stacks 在本演练中部署到实例的应用程序。
要查看应用程序的源代码,请将opsworks-windows-demo-nodejs/srv/mylinuxdemoapp
目录的内容。
index.js
文件包含该应用程序最重要的代码:
var express = require('express');
var app = express();
var path = require('path');
var os = require('os');
var bodyParser = require('body-parser');
var fs = require('fs');
var add_comment = function(comment) {
var comments = get_comments();
comments.push({"date": new Date(), "text": comment});
fs.writeFileSync('./comments.json', JSON.stringify(comments));
};
var get_comments = function() {
var comments;
if (fs.existsSync('./comments.json')) {
comments = fs.readFileSync('./comments.json');
comments = JSON.parse(comments);
} else {
comments = [];
}
return comments;
};
app.use(function log (req, res, next) {
console.log([req.method, req.url].join(' '));
next();
});
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: false }))
app.set('view engine', 'jade');
app.get('/', function(req, res) {
var comments = get_comments();
res.render("index",
{ agent: req.headers['user-agent'],
hostname: os.hostname(),
nodeversion: process.version,
time: new Date(),
admin: (process.env.APP_ADMIN_EMAIL || "admin@unconfigured-value.com" ),
comments: get_comments()
});
});
app.post('/', function(req, res) {
var comment = req.body.comment;
if (comment) {
add_comment(comment);
console.log("Got comment: " + comment);
}
res.redirect("/#form-section");
});
var server = app.listen(process.env.PORT || 3000, function() {
console.log('Listening on %s', process.env.PORT);
});
下面是该文件执行的操作:
-
require
加载模块,这些模块中包含此 Web 应用程序按预期运行所需要的一些相关代码。 -
add_comment
和get_comments
函数将信息写入comments.json
文件并从中读取信息。 -
有关
app.get
、app.listen
、app.post
、app.set
和app.use
的信息,请参阅 Express API 参考。
要了解如何创建和打包应用程序以便部署,请参阅应用程序源。