第 2 章 开发和部署 Node.js 应用程序

您可以创建新的 Node.js 应用并将其部署到 OpenShift。

2.1. 开发 Node.js 应用程序

对于基本 Node.js 应用,您必须创建一个 JavaScript 文件,其中包含 Node.js 方法。

先决条件

  • npm 已安装。

流程

  1. 创建新目录 myApp,再导航到它。

    $ mkdir myApp
    $ cd MyApp

    这是应用的根目录。

  2. 使用 npm 初始化应用程序。

    本例的其余部分假定入口点是 app.js,在运行 npm init 时会提示您输入设置。

    $ cd myApp
    $ npm init
  3. 在名为 app.js 的新文件中创建入口点。

    app.js示例

    const http = require('http');
    
    const server = http.createServer((request, response) => {
      response.statusCode = 200;
      response.setHeader('Content-Type', 'application/json');
    
      const greeting = {content: 'Hello, World!'};
    
      response.write(JSON.stringify(greeting));
      response.end();
    });
    
    server.listen(8080, () => {
      console.log('Server running at http://localhost:8080');
    });

  4. 启动应用程序。

    $ node app.js
    Server running at http://localhost:8080
  5. 使用 curl 或浏览器,验证您的应用程序是否在 http://localhost:8080 中运行。

    $ curl http://localhost:8080
    {"content":"Hello, World!"}

附加信息