本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
了解更多:探索本演练中用到的应用程序
重要
AWS OpsWorks Stacks 不再接受新客户。在 2024 年 5 月 26 日之前,现有客户将能够照常使用 OpsWorks 控制台、API、CLI 和 CloudFormation 资源,届时这些工具或资源将停用。为准备此过渡,我们建议您尽快将堆栈过渡到AWS Systems Manager。有关更多信息,请参阅 AWS OpsWorks Stacks 生命周期终止常见问题解答 和 将 AWS OpsWorks Stacks 应用程序迁移到 AWS Systems Manager Application Manager:
本主题介绍 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 参考。
要了解如何创建和打包应用程序以便部署,请参阅应用程序源。