🎊 【Node.js】如何使用 Node.js

【Node.js】如何使用 Node.js

使用 Node.js 主要涉及理解其核心概念、运行 JavaScript 代码、管理依赖、构建应用以及利用其生态系统。以下是详细指南,涵盖 Node.js 的基本使用方法、核心功能、常见场景、代码示例和最佳实践,帮助快速上手。

1. 了解 Node.js 的基础

Node.js 是一个服务器端 JavaScript 运行时,适合构建 Web 服务器、API、实时应用等。使用 Node.js 前,需掌握:

JavaScript 基础:熟悉 ES6+ 语法(如箭头函数、Promise、async/await)。异步编程:Node.js 依赖回调、Promise 或 async/await 处理异步操作。模块化:Node.js 使用 CommonJS(require)或 ES 模块(import)组织代码。

确保已安装 Node.js 和 NPM(参考上一回答的安装步骤),并验证:

node -v # 检查 Node.js 版本

npm -v # 检查 NPM 版本

2. 基本使用方法

Node.js 提供多种方式运行代码,以下是核心使用场景:

(1) 运行 JavaScript 文件

创建一个 JavaScript 文件,例如 app.js:console.log('Hello, Node.js!');

在终端运行:node app.js

输出:Hello, Node.js!

(2) 使用 Node.js REPL

REPL(Read-Eval-Print Loop)是一个交互式环境,适合测试代码:

打开终端,输入:node

进入 REPL 模式,输入 JavaScript 代码:> console.log('Test');

Test

> 1 + 2

3

退出 REPL:按 Ctrl+C 两次或输入 .exit。

(3) 创建简单的 HTTP 服务器

Node.js 内置 http 模块可快速创建 Web 服务器:

const http = require('http');

const server = http.createServer((req, res) => {

res.writeHead(200, { 'Content-Type': 'text/plain' });

res.end('Hello from Node.js server!');

});

server.listen(3000, () => {

console.log('Server running at http://localhost:3000/');

});

保存为 server.js,运行 node server.js。访问 http://localhost:3000,浏览器显示 Hello from Node.js server!。

3. 使用 NPM 管理项目和依赖

NPM 是 Node.js 的包管理器,用于安装模块和初始化项目。

(1) 初始化项目

创建项目文件夹并进入:mkdir my-node-app

cd my-node-app

初始化项目,生成 package.json:npm init -y

package.json 记录项目信息和依赖。

(2) 安装依赖

安装第三方模块,例如 Express(流行的 Web 框架):npm install express

依赖会记录在 package.json 中,安装到 node_modules 文件夹。全局安装(不推荐,除非是工具):npm install -g nodemon

(3) 运行脚本

编辑 package.json,添加脚本:

"scripts": {

"start": "node app.js",

"dev": "nodemon app.js"

}

运行:npm start # 运行 app.js

npm run dev # 使用 nodemon 自动重启

4. 核心模块和功能

Node.js 提供内置模块,无需安装即可使用。以下是常用模块及其用法:

(1) 文件系统操作(fs)

fs 模块用于读写文件,支持同步和异步操作。

const fs = require('fs');

// 异步读取文件

fs.readFile('example.txt', 'utf8', (err, data) => {

if (err) throw err;

console.log(data);

});

// 异步写入文件

fs.writeFile('example.txt', 'Hello, Node.js!', (err) => {

if (err) throw err;

console.log('File written successfully');

});

(2) 路径操作(path)

path 模块处理文件路径,跨平台兼容。

const path = require('path');

// 获取文件名

console.log(path.basename('/home/user/file.txt')); // file.txt

// 拼接路径

console.log(path.join(__dirname, 'data', 'file.json')); // 当前目录/data/file.json

(3) 事件处理(events)

events 模块实现自定义事件监听。

const EventEmitter = require('events');

const emitter = new EventEmitter();

// 监听事件

emitter.on('greet', (name) => {

console.log(`Hello, ${name}!`);

});

// 触发事件

emitter.emit('greet', 'Alice');

(4) 流处理(stream)

stream 模块处理大数据,适合文件或网络数据流。

const fs = require('fs');

const readStream = fs.createReadStream('large.txt');

const writeStream = fs.createWriteStream('output.txt');

readStream.pipe(writeStream); // 流式传输数据

5. 构建 Web 应用(使用 Express)

Express 是最流行的 Node.js Web 框架,简化了路由和中间件处理。

安装 Express

npm install express

创建简单的 Express 应用

const express = require('express');

const app = express();

// 路由:GET 请求

app.get('/', (req, res) => {

res.send('Welcome to my Node.js app!');

});

// 路由:动态参数

app.get('/user/:id', (req, res) => {

res.send(`User ID: ${req.params.id}`);

});

// 启动服务器

app.listen(3000, () => {

console.log('Server running at http://localhost:3000/');

});

保存为 app.js,运行 node app.js。访问 http://localhost:3000 或 http://localhost:3000/user/123。

添加中间件

中间件处理请求前的逻辑,如解析 JSON:

app.use(express.json()); // 解析 JSON 请求体

app.post('/data', (req, res) => {

console.log(req.body); // 打印请求体

res.json({ message: 'Data received' });

});

6. 异步编程

Node.js 的异步特性是核心,以下是三种处理方式:

(1) 回调

const fs = require('fs');

fs.readFile('file.txt', 'utf8', (err, data) => {

if (err) throw err;

console.log(data);

});

(2) Promise

const fs = require('fs').promises;

fs.readFile('file.txt', 'utf8')

.then((data) => console.log(data))

.catch((err) => console.error(err));

(3) async/await

const fs = require('fs').promises;

async function readFile() {

try {

const data = await fs.readFile('file.txt', 'utf8');

console.log(data);

} catch (err) {

console.error(err);

}

}

readFile();

推荐:使用 async/await,代码更简洁、可读性更高。

7. 连接数据库

Node.js 支持多种数据库,以下是 MongoDB(NoSQL)和 MySQL(SQL)的示例。

MongoDB(使用 Mongoose)

安装 Mongoose:npm install mongoose

连接并操作:const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/mydb', {

useNewUrlParser: true,

useUnifiedTopology: true,

});

const UserSchema = new mongoose.Schema({ name: String });

const User = mongoose.model('User', UserSchema);

async function addUser() {

const user = new User({ name: 'Alice' });

await user.save();

console.log('User saved');

}

addUser();

MySQL

安装 MySQL 驱动:npm install mysql2

连接并查询:const mysql = require('mysql2/promise');

async function query() {

const connection = await mysql.createConnection({

host: 'localhost',

user: 'root',

password: 'your_password',

database: 'mydb',

});

const [rows] = await connection.execute('SELECT * FROM users');

console.log(rows);

await connection.end();

}

query();

8. 部署 Node.js 应用

将应用部署到服务器(如 Vercel、Heroku、AWS):

确保 package.json 有 start 脚本:"scripts": {

"start": "node app.js"

}

指定 Node.js 版本(可选):

在 package.json 中添加:"engines": {

"node": "20.x"

}

部署到 Vercel(简单示例):

安装 Vercel CLI:npm install -g vercel。运行 vercel 命令,按提示配置项目。

使用 PM2 管理进程(生产环境):npm install -g pm2

pm2 start app.js

9. 最佳实践

代码组织:将路由、控制器、模型分开,使用模块化。错误处理:app.use((err, req, res, next) => {

console.error(err.stack);

res.status(500).send('Something went wrong!');

});

环境变量:使用 dotenv 管理配置:npm install dotenv

require('dotenv').config();

console.log(process.env.PORT);

日志记录:使用 winston 或 morgan 记录请求和错误。测试:使用 Jest 或 Mocha 编写单元测试。性能优化:使用集群模块(cluster)或 Worker Threads 处理多核 CPU。

10. 示例项目:简单的 TODO API

以下是一个使用 Express 和内存存储的 TODO API:

const express = require('express');

const app = express();

app.use(express.json());

let todos = [];

// 获取所有 TODO

app.get('/todos', (req, res) => {

res.json(todos);

});

// 添加 TODO

app.post('/todos', (req, res) => {

const todo = { id: todos.length + 1, task: req.body.task };

todos.push(todo);

res.status(201).json(todo);

});

// 删除 TODO

app.delete('/todos/:id', (req, res) => {

todos = todos.filter((todo) => todo.id !== parseInt(req.params.id));

res.json({ message: 'Todo deleted' });

});

app.listen(3000, () => {

console.log('Server running at http://localhost:3000/');

});

运行:node app.js。测试:

curl -X POST http://localhost:3000/todos -H "Content-Type: application/json" -d '{"task":"Learn Node.js"}'curl http://localhost:3000/todos

11. 学习建议

实践:从简单服务器开始,逐步尝试 Express、数据库、WebSocket。项目:构建博客、聊天应用或电商 API。资源:

Node.js 官方文档:https://nodejs.org/en/docs/教程:FreeCodeCamp、Bilibili Node.js 课程。书籍:《Node.js in Action》、《Learning Node.js》。

社区:Stack Overflow、Node.js Slack、GitHub。

12. 总结

使用 Node.js 涉及运行 JavaScript 代码、管理依赖、利用内置模块和框架(如 Express)构建应用。通过掌握异步编程、模块化开发和生态工具,可以快速构建高效的服务器端应用。

🎈 相关推荐

窝子的成语(形容窝多的成语)(40个)
🏷️ 2022年bet体育365官网合法吗

窝子的成语(形容窝多的成语)(40个)

📅 10-13 👀 8669
魔兽世界术士必看!绿火任务核心道具《失落军团的封印书典》全解析与高效获取指南
简易征收是什么意思?
🏷️ 足球比分365cv

简易征收是什么意思?

📅 08-13 👀 5398
天猫成交账单查看位置在哪?作者:小果 时间:2025-10-14 阅读:6532
七彩虹GTX960性能怎么样 必看:七彩虹GTX960性能测试
🏷️ 日博官网365bet

七彩虹GTX960性能怎么样 必看:七彩虹GTX960性能测试

📅 08-08 👀 4556
《烟雨江湖》桐木采集点分享 桐木在哪里采集
🏷️ 日博官网365bet

《烟雨江湖》桐木采集点分享 桐木在哪里采集

📅 10-25 👀 3343