Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行时环境。它允许开发者使用 JavaScript 代码编写服务器端应用程序,同时也支持构建高性能、可扩展的网络应用程序。
安装 Node.js
首先,您需要在您的计算机上安装 Node.js。您可以从 Node.js 官网 下载最新版本的 Node.js 安装包。
$ npm install -g nodejs
Hello World
下面是一个简单的 Node.js "Hello World" 示例:
// 导入 http 模块
const http = require('http');
// 创建服务器
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World\n');
});
// 监听 8080 端口
server.listen(8080, () => {
console.log('服务器运行在 http://localhost:8080/');
});
保存以上代码为 server.js
,然后在终端中运行以下命令启动服务器:
$ node server.js
在浏览器中访问 http://localhost:8080/
,您将看到 "Hello World" 文本。
事件循环
Node.js 使用单线程和事件驱动模型,这意味着它在同一时间内只能执行一个任务。但是,通过事件循环机制,Node.js 可以处理多个并发连接。
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World\n');
});
server.listen(8080);
console.log('服务器运行在 http://localhost:8080/');
// 事件循环
process.on('exit', () => {
console.log('服务器关闭');
});
在这个示例中,即使服务器已经关闭,控制台仍然会输出 "服务器关闭" 信息,因为事件循环机制在后台继续运行。
完整教程
您可以访问本站提供的完整 Node.js 教程,了解更多高级特性:Node.js 教程