引言
Node.js作为一款流行的JavaScript运行环境,以其高性能和跨平台特性被广泛应用于服务器端编程、实时应用开发等领域。本文将为您带来50个精选的Node.js代码实例,帮助您快速上手并掌握Node.js的核心技能。
1. Hello World
// index.js
console.log('Hello, World!');
这是一个最简单的Node.js程序,用于输出“Hello, World!”。
2. 文件读取
const fs = require('fs');
const path = require('path');
fs.readFile(path.join(__dirname, 'example.txt'), 'utf8', (err, data) => {
if (err) {
return console.error(err);
}
console.log(data);
});
此代码示例展示了如何使用Node.js读取文件内容。
3. 文件写入
const fs = require('fs');
const path = require('path');
const data = 'Hello, World!';
fs.writeFile(path.join(__dirname, 'example.txt'), data, (err) => {
if (err) {
return console.error(err);
}
console.log('Data written to file');
});
此代码示例展示了如何将数据写入文件。
4. 异步编程
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function asyncExample() {
console.log('Start delay');
await delay(1000);
console.log('End delay');
}
asyncExample();
此代码示例展示了如何使用async/await进行异步编程。
5. 模块导入
// math.js
exports.add = (a, b) => a + b;
// index.js
const math = require('./math');
console.log(math.add(2, 3)); // 输出 5
此代码示例展示了如何导入和使用模块。
6. 事件监听
const EventEmitter = require('events');
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
myEmitter.on('event', () => {
console.log('An event occurred!');
});
myEmitter.emit('event');
此代码示例展示了如何使用事件监听器。
7. HTTP服务器
const http = require('http');
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, World!\n');
});
server.listen(3000, () => {
console.log('Server running on port 3000');
});
此代码示例展示了如何创建一个简单的HTTP服务器。
8. 使用Express框架
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
此代码示例展示了如何使用Express框架创建一个简单的Web应用。
9. 使用Mongoose操作MongoDB
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/mydatabase', { useNewUrlParser: true, useUnifiedTopology: true });
const Schema = mongoose.Schema;
const UserSchema = new Schema({
name: String,
age: Number
});
const User = mongoose.model('User', UserSchema);
const user = new User({ name: 'John', age: 30 });
user.save().then(() => console.log('User saved'));
此代码示例展示了如何使用Mongoose操作MongoDB。
10. 使用Redis缓存
const redis = require('redis');
const client = redis.createClient();
client.set('key', 'value', redis.print);
client.get('key', (err, reply) => {
console.log(reply); // 输出 value
});
此代码示例展示了如何使用Redis进行数据缓存。
11. 使用NPM包管理器
# 安装一个NPM包
npm install express
# 创建一个package.json文件
npm init -y
此代码示例展示了如何使用NPM包管理器安装和使用NPM包。
12. 使用npm scripts
// package.json
{
"scripts": {
"start": "node index.js"
}
}
此代码示例展示了如何使用npm scripts来运行Node.js程序。
13. 使用PM2进程管理器
# 安装PM2
npm install pm2 -g
# 启动PM2守护进程
pm2 start index.js
此代码示例展示了如何使用PM2进程管理器来管理Node.js应用。
14. 使用环境变量
require('dotenv').config();
console.log(process.env.DB_HOST); // 输出数据库主机地址
此代码示例展示了如何使用环境变量来配置应用。
15. 使用async库进行异步编程
const async = require('async');
async function doSomething() {
return 'Hello, World!';
}
doSomething().then(result => console.log(result));
此代码示例展示了如何使用async库进行异步编程。
16. 使用Promise进行异步编程
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
delay(1000).then(() => console.log('Done!'));
此代码示例展示了如何使用Promise进行异步编程。
17. 使用事件循环
setInterval(() => {
console.log('Tick');
}, 1000);
此代码示例展示了如何使用事件循环。
18. 使用Buffer处理二进制数据
const buffer = Buffer.from('Hello, World!', 'utf8');
console.log(buffer.toString()); // 输出 Hello, World!
此代码示例展示了如何使用Buffer处理二进制数据。
19. 使用Stream处理文件流
const fs = require('fs');
const readStream = fs.createReadStream('example.txt');
const writeStream = fs.createWriteStream('example_copy.txt');
readStream.pipe(writeStream);
此代码示例展示了如何使用Stream处理文件流。
20. 使用HTTP客户端
const http = require('http');
http.get('http://example.com', (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
console.log(data);
});
});
此代码示例展示了如何使用HTTP客户端获取网页内容。
21. 使用HTTPS客户端
const https = require('https');
https.get('https://example.com', (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
console.log(data);
});
});
此代码示例展示了如何使用HTTPS客户端获取网页内容。
22. 使用WebSocket
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('received: %s', message);
});
});
此代码示例展示了如何使用WebSocket进行实时通信。
23. 使用CORS跨源资源共享
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors());
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
此代码示例展示了如何使用CORS跨源资源共享。
24. 使用JWT进行身份验证
const jwt = require('jsonwebtoken');
const token = jwt.sign({ id: 1 }, 'secret', { expiresIn: '1h' });
console.log(token); // 输出 JWT token
const decoded = jwt.verify(token, 'secret');
console.log(decoded); // 输出解码后的信息
此代码示例展示了如何使用JWT进行身份验证。
25. 使用bcrypt进行密码加密
const bcrypt = require('bcrypt');
bcrypt.hash('password', 10, (err, hash) => {
if (err) {
return console.error(err);
}
console.log(hash); // 输出加密后的密码
});
bcrypt.compare('password', hash, (err, res) => {
if (err) {
return console.error(err);
}
console.log(res); // 输出比较结果
});
此代码示例展示了如何使用bcrypt进行密码加密。
26. 使用Promise.all处理多个异步操作
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
async function asyncExample() {
const [a, b, c] = await Promise.all([delay(1000), delay(2000), delay(3000)]);
console.log(a, b, c); // 输出 1 2 3
}
asyncExample();
此代码示例展示了如何使用Promise.all处理多个异步操作。
27. 使用async/await处理异步操作
async function asyncExample() {
const a = await delay(1000);
const b = await delay(2000);
const c = await delay(3000);
console.log(a, b, c); // 输出 1 2 3
}
asyncExample();
此代码示例展示了如何使用async/await处理异步操作。
28. 使用Promise.race处理超时
function delay(ms) {
return new Promise((resolve, reject) => {
setTimeout(resolve, ms);
});
}
Promise.race([delay(1000), delay(2000), delay(3000)])
.then(() => console.log('Done!'))
.catch(() => console.log('Timeout!'));
此代码示例展示了如何使用Promise.race处理超时。
29. 使用Promise.reject处理错误
function delay(ms) {
return new Promise((resolve, reject) => {
setTimeout(() => reject(new Error('Failed to complete the task!')), ms);
});
}
delay(1000)
.then(() => console.log('Done!'))
.catch((err) => console.error(err.message));
此代码示例展示了如何使用Promise.reject处理错误。
30. 使用Stream转换数据
const { Transform } = require('stream');
const uppercaseTransform = new Transform({
transform(chunk, encoding, callback) {
const upper = chunk.toString().toUpperCase();
this.push(upper);
callback();
}
});
const fs = require('fs');
const { Transform } = require('stream');
const readStream = fs.createReadStream('example.txt');
const writeStream = fs.createWriteStream('example_uppercase.txt');
readStream
.pipe(uppercaseTransform)
.pipe(writeStream)
.on('finish', () => console.log('Conversion complete'));
此代码示例展示了如何使用Stream转换数据。
31. 使用HTTP代理
const http = require('http');
const httpProxy = require('http-proxy');
const proxy = httpProxy.createProxyServer({});
const server = http.createServer((req, res) => {
proxy.web(req, res, { target: 'http://example.com' });
});
server.listen(3000);
此代码示例展示了如何使用HTTP代理。
32. 使用WebSocket代理
const { createServer } = require('http');
const { WebSocketServer } = require('ws');
const httpProxy = require('http-proxy');
const proxy = httpProxy.createProxyServer({});
const server = createServer((req, res) => {
proxy.web(req, res, { target: 'http://example.com' });
});
const wss = new WebSocketServer({ server });
wss.on('connection', (ws) => {
ws.on('message', (data) => {
proxy.web(ws, null, { target: 'ws://example.com' });
});
});
server.listen(3000);
此代码示例展示了如何使用WebSocket代理。
33. 使用Socket.IO实现实时通信
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = socketIo(server);
io.on('connection', (socket) => {
socket.on('chat message', (msg) => {
io.emit('chat message', msg);
});
});
server.listen(3000);
此代码示例展示了如何使用Socket.IO实现实时通信。
34. 使用Redis进行分布式锁
const redis = require('redis');
const client = redis.createClient();
const lockKey = 'myLock';
const lockValue = 'myLockValue';
client.set(lockKey, lockValue, 'NX', 'PX', 1000, (err) => {
if (err) {
console.error('Lock acquisition failed:', err);
return;
}
console.log('Lock acquired!');
// ...执行需要锁定的代码
client.del(lockKey, (err) => {
if (err) {
console.error('Lock release failed:', err);
return;
}
console.log('Lock released!');
});
});
此代码示例展示了如何使用Redis进行分布式锁。
35. 使用Kafka进行消息队列
const kafka = require('kafka-node');
const Producer = kafka.Producer;
const Client = kafka.KafkaClient;
const KeyedMessage = kafka.KeyedMessage;
const client = new Client({ kafkaHost: 'localhost:9092' });
const producer = new Producer(client);
producer.on('ready', () => {
console.log('Producer ready');
const messages = [
new KeyedMessage('myTopic', 'Hello, World!', 'key1'),
new KeyedMessage('myTopic', 'Hello, Kafka!', 'key2')
];
producer.send(messages, (err, data) => {
if (err) {
console.error('Failed to send message:', err);
return;
}
console.log('Message sent:', data);
});
});
此代码示例展示了如何使用Kafka进行消息队列。
36. 使用RabbitMQ进行消息队列
const amqp = require('amqplib/callback_api');
amqp.connect('amqp://localhost', (err, conn) => {
conn.createChannel((err, ch) => {
const q = 'myQueue';
ch.assertQueue(q, { durable: false });
ch.sendToQueue(q, Buffer.from('Hello, RabbitMQ!'));
console.log(' [x] Sent "Hello, RabbitMQ!"');
});
setTimeout(() => {
conn.close();
process.exit(0);
}, 500);
});
此代码示例展示了如何使用RabbitMQ进行消息队列。
37. 使用Elasticsearch进行搜索
const elasticsearch = require('elasticsearch');
const client = new elasticsearch.Client({ host: 'localhost:9200' });
client.indices.create({
index: 'myindex',
body: {
settings: {
number_of_shards: 1,
number_of_replicas: 0
},
mappings: {
properties: {
name: { type: 'text' }
}
}
}
});
client.index({
index: 'myindex',
body: {
name: 'John Doe'
}
});
client.search({
index: 'myindex',
body: {
query: {
match: { name: 'John Doe' }
}
}
}).then((response) => {
console.log('Response:', response);
});
此代码示例展示了如何使用Elasticsearch进行搜索。
38. 使用Cassandra进行数据存储
const cassandra = require('cassandra-driver');
const client = new cassandra.Client({ contactPoints: ['127.0.0.1'], localDataCenter: 'datacenter1' });
client.connect()
.then(() => {
const query = 'SELECT * FROM mytable';
return client.execute(query);
})
.then(result => {
console.log(result);
})
.catch(err => {
console.error(err);
});
此代码示例展示了如何使用Cassandra进行数据存储。
39. 使用PostgreSQL进行数据存储
const { Pool } = require('pg');
const pool = new Pool({
user: 'myuser',
host: 'localhost',
database: 'mydatabase',
password: 'mypassword',
port: 5432,
});
pool.query('SELECT * FROM mytable', (err, res) => {
if (err) {
return console.error(err);
}
console.log(res.rows);
pool.end();
});
此代码示例展示了如何使用PostgreSQL进行数据存储。
40. 使用MySQL进行数据存储
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user: 'myuser',
password: 'mypassword',
database: 'mydatabase'
});
connection.connect();
connection.query('SELECT * FROM mytable', (err, results, fields) => {
if (err) {
throw err;
}
console.log(results);
connection.end();
});
此代码示例展示了如何使用MySQL进行数据存储。
41. 使用MongoDB进行数据存储
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/mydatabase', { useNewUrlParser: true, useUnifiedTopology: true });
const Schema = mongoose.Schema;
const UserSchema = new Schema({
name: String,
age: Number
});
const User = mongoose.model('User', UserSchema);
const user = new User({ name: 'John', age: 30 });
user.save().then(() => console.log('User saved'));
此代码示例展示了如何使用MongoDB进行数据存储。
42. 使用Redis进行数据缓存
const redis = require('redis');
const client = redis.createClient();
client.set('key', 'value', redis.print);
client.get('key', (err, reply) => {
console.log(reply); // 输出 value
});
此代码示例展示了如何使用Redis进行数据缓存。
43. 使用JWT进行身份验证
const jwt = require('jsonwebtoken');
const token = jwt.sign({ id: 1 }, 'secret', { expiresIn: '1h' });
console.log(token); // 输出 JWT token
const decoded = jwt.verify(token, 'secret');
console.log(decoded); // 输出解码后的信息
此代码示例展示了如何使用JWT进行身份验证。
44. 使用bcrypt进行密码加密
”`javascript const bcrypt = require(‘bcrypt’);
bcrypt.hash(’
