

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 深入了解：探索本演練中使用的應用程式
<a name="gettingstarted-linux-explore-app-source"></a>

**重要**  
 AWS OpsWorks Stacks 此服務已於 2024 年 5 月 26 日終止，並已針對新客戶和現有客戶停用。我們強烈建議客戶盡快將其工作負載遷移至其他解決方案。如果您對遷移有任何疑問，請透過 [AWS re：Post](https://repost.aws/) 或透過 [AWS Premium Support](https://aws.amazon.com/support) 聯絡 AWS 支援 團隊。

本主題說明 OpsWorks Stacks 為此演練部署至執行個體的應用程式。

若要查看應用程式的來源碼，請將 [opsworks-windows-demo-nodejs](https://github.com/awslabs/opsworks-windows-demo-nodejs) GitHub 儲存庫內容擷取到本機工作站的空目錄中。您也可以登入已部署技術指南的執行個體，來探索 `/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 參考](http://expressjs.com/4x/api.html)。

 若要了解如何建立和封裝您的應用程式以便部署，請參閱 [應用程式來源](workingapps-creating.md#workingapps-creating-source)。