第 2 章 开发和部署 Node.js 应用程序
您可以创建新的 Node.js 应用并将其部署到 OpenShift。
2.1. 开发 Node.js 应用程序
对于基本 Node.js 应用,您必须创建一个 JavaScript 文件,其中包含 Node.js 方法。
先决条件
-
npm
已安装。
流程
创建新目录
myApp
,再导航到它。$ mkdir myApp $ cd MyApp
这是应用的根目录。
使用
npm
初始化应用程序。本例的其余部分假定入口点是
app.js
,在运行npm init
时会提示您输入设置。$ cd myApp $ npm init
在名为
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'); });
启动应用程序。
$ node app.js Server running at http://localhost:8080
使用
curl
或浏览器,验证您的应用程序是否在http://localhost:8080
中运行。$ curl http://localhost:8080 {"content":"Hello, World!"}
附加信息
- Node.js 运行时提供核心 Node.js API,记录在 Node.js API 文档中。