2026/8/28 15:23:50

【前端开发-----NodeJS】Node.js 快速入门教程:一篇文章搞定

【前端开发-----NodeJS】Node.js 快速入门教程:一篇文章搞定 Node.js 是前端开发人员进军后端的重要工具之一。本文将带领你从 0 开始了解 Node.js 的基本概念、安装配置、核心模块及实战案例让你快速入门 Node.js### 一、什么是 Node.jsNode.js 是一个基于 Chrome V8 引擎的 JavaScript 运行环境它能够让 JavaScript 不仅运行在浏览器内还能用于服务器端开发。Node.js 提供了一整套工具和模块使 JavaScript 在服务器端可以处理文件、数据库和 HTTP 请求等任务。### 二、Node.js 的安装#### 1. 下载 Node.js前往 Node.js 官方网站https://nodejs.org/下载适合你操作系统的安装包。推荐选择 LTS长期支持版更加稳定。#### 2. 安装并验证1. 下载完成后运行安装文件一路点击“下一步”完成安装。 2. 安装完成后打开命令行Windows 上是 CMD 或 PowerShellmacOS 是 Terminal输入以下命令验证是否安装成功 node -v npm -v 以上命令会输出 Node.js 和 npm 的版本号表明安装成功。 ### 三、Node.js 核心概念#### 1. 模块化Node.js 使用模块化开发模式。每个文件都可以看作是一个模块可以通过require引用其他模块。#### 2. 同步与异步Node.js 支持非阻塞的异步操作这是它在高并发场景下表现优异的原因。#### 3. 事件驱动Node.js 采用事件驱动的方式当事件触发时会执行回调函数。### 四、Node.js 入门代码示例#### 1. Hello, World!新建一个hello.js文件输入以下代码 console.log(“Hello, World!”); 在命令行中运行 node hello.js 输出 Hello, World! #### 2. 搭建第一个 HTTP 服务器Node.js 内置了http模块可以轻松创建 HTTP 服务器。 // server.js const http require(‘http’); const server http.createServer((req, res) { res.statusCode 200; res.setHeader(‘Content-Type’, ‘text/plain’); res.end(‘Hello, Node.js Server! ‘); }); server.listen(3000, () { console.log(‘服务器运行在 http://localhost:3000’); }); 运行此代码后访问 http://localhost:3000 就能看到Hello, Node.js Server!的内容。#### 3. 使用模块化创建和调用模块1. 创建一个math.js文件定义一个简单的加法函数 // math.js function add(a, b) { return a b; } module.exports { add }; 2. 在主文件app.js中使用require引入模块 // app.js const math require(’./math’); const result math.add(2, 3); console.log(“2 3 ”, result); 运行app.js会看到输出 2 3 5 ### 五、Node.js 常用模块#### 1. 文件系统模块fsNode.js 提供fs模块用于文件的读写操作。##### 示例读取文件内容 const fs require(‘fs’); fs.readFile(‘example.txt’, ‘utf8’, (err, data) { if (err) { console.error(err); return; } console.log(data); }); #### 2. 路径模块pathpath模块用于处理和转换文件路径。 const path require(‘path’); const fullPath path.join(__dirname, ‘example’, ‘test.txt’); console.log(fullPath); // 输出完整路径 #### 3. URL 模块urlurl模块提供了对 URL 字符串的解析、拼接等操作。 const url require(‘url’); const myURL new URL(‘https://www.example.com:8000/path/name?foobar#hash’); console.log(myURL.hostname); // 输出www.example.com console.log(myURL.searchParams.get(‘foo’)); // 输出bar ### 六、Node.js 异步编程与回调#### 1. 使用回调函数 const fs require(‘fs’); fs.readFile(‘example.txt’, ‘utf8’, (err, data) { if (err) throw err; console.log(data); }); #### 2. 使用 PromiseNode.js 也支持使用 Promise 来处理异步操作 const fs require(‘fs’).promises; fs.readFile(‘example.txt’, ‘utf8’) .then(data { console.log(data); }) .catch(err { console.error(err); }); #### 3. 使用 Async/Await在 Node.js 中使用async/await可以更加简洁地处理异步逻辑 const fs require(‘fs’).promises; async function readFile() { try { const data await fs.readFile(‘example.txt’, ‘utf8’); console.log(data); } catch (err) { console.error(err); } } readFile(); ### 七、Node.js 项目实战简易 API 接口以下代码实现了一个简单的 API 服务可以处理 HTTP 请求并返回 JSON 数据。#### 1. 创建apiServer.jsconst http require(‘http’); const server http.createServer((req, res) { res.setHeader(‘Content-Type’, ‘application/json’); res.setHeader(‘Access-Control-Allow-Origin’, ‘*’); if (req.url ‘/api’ req.method ‘GET’) { const data { message: ‘Hello from Node.js API!’ }; res.writeHead(200); res.end(JSON.stringify(data)); } else { res.writeHead(404); res.end(JSON.stringify({ error: ‘Resource not found’ })); } }); server.listen(4000, () { console.log(‘API server running on http://localhost:4000’); }); #### 2. 启动 API 服务器在终端运行以下命令启动服务器 node apiServer.js 打开浏览器或使用 API 测试工具访问 http://localhost:4000/api应该会得到如下响应 { “message”: “Hello from Node.js API!” } ### 八、总结通过本篇文章你应该已经掌握了 Node.js 的基础操作了解了如何创建和使用模块、如何处理文件系统以及如何构建一个简单的 HTTP 服务器。掌握 Node.js 的这些基础知识后你可以进一步学习 Express 框架、数据库连接、WebSocket 等内容不断扩展 Node.js 的使用场景。希望这篇文章能帮助你快速入门 Node.js