如何在 node.js 中创建和运行文件

How to create and run a file in node.js

本文关键字:创建 运行 文件 js node      更新时间:2023-09-26

我安装了node.js新版本,并使用node-v和npm-v签入命令提示符我想知道如何创建和运行该文件。

在项目的根目录中创建文件 hello.js,并使用以下代码填充它:

var http = require("http");
http.createServer(function(request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.write("Hello World");
  response.end();
}).listen(8888);

首先,在命令提示符下使用 Node.js 执行脚本:

node hello.js

打开浏览器并将其指向 http://localhost:8888/ .您将看到一条消息 "你好世界" .

您可以像这样启动 Node.js 过程:

% node example.js
Server running at http://127.0.0.1:1337/