原文地址:How to Turn Your Device Into a Simple Server Using Node.js
原文作者:Trix Cyrus

让我们一起在你的设备上部署一个简单的 Node.js。

入门

首先,让我们使用 Node.js 创建一个基础的服务。步骤如下:

创建一个 node-server 目录:

1
2
mkdir node-server
cd node-server

初始化一个 Node.js 项目:

1
npm init -y

安装依赖:

1
npm install express ws multer mongoose dotenv helmet morgan cluster compression
  • express:处理 HTTP 请求
  • ws:支持 Websocket
  • multer:处理文件上传
  • mongoose:MongoDB 链接
  • dotenv:读取环境变量
  • helmet:保护服务器安全
  • morgan:日志
  • cluster:多线程
  • compression:用于压缩响应数据

创建一个 .env 文件

在项目根目录,创建一个 .env 文件,它的作用是用来存储环境变量:

1
2
PORT=8080
MONGO_URI=mongodb://localhost:27017/serverdb

创建一个 server.js 文件:

1
2
touch server.js
nano server.js

粘贴下面的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
require('dotenv').config();
const express = require('express');
const ws = require('ws');
const http = require('http');
const multer = require('multer');
const mongoose = require('mongoose');
const helmet = require('helmet');
const morgan = require('morgan');
const cluster = require('cluster');
const os = require('os');
const compression = require('compression');
const fs = require('fs');
const path = require('path');

const PORT = process.env.PORT || 8080;
const MONGO_URI = process.env.MONGO_URI;
const NUM_CPUS = os.cpus().length;

if (cluster.isMaster) {
console.log(`Master process is running. Spawning ${NUM_CPUS} workers...`);
for (let i = 0; i < NUM_CPUS; i++) {
cluster.fork();
}

cluster.on('exit', (worker, code, signal) => {
console.log(`Worker ${worker.process.pid} died. Spawning a new worker.`);
cluster.fork();
});
} else {
const app = express();
const server = http.createServer(app);
const wss = new ws.Server({ server });

mongoose.connect(MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('Connected to MongoDB'))
.catch(err => console.error('MongoDB connection error:', err));

app.use(express.json());
app.use(helmet());
app.use(morgan('common'));
app.use(compression());

const upload = multer({ dest: 'uploads/' });

app.use(express.static(path.join(__dirname, 'public')));

app.use((req, res, next) => {
console.log(`Received ${req.method} request for ${req.url}`);
next();
});

wss.on('connection', (socket) => {
console.log('WebSocket connection established.');
socket.on('message', (message) => {
console.log(`Received WebSocket message: ${message}`);
socket.send(`Message received: ${message}`);
});
});

app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

app.get('/api/data', async (req, res) => {
res.json({ message: 'Server API Response', data: [] });
});

app.post('/upload', upload.single('file'), (req, res) => {
console.log('File uploaded:', req.file);
res.status(201).json({ message: 'File uploaded successfully', file: req.file });
});

app.get('/greet/:name', (req, res) => {
const name = req.params.name || 'stranger';
res.send(`<h1>Hello, ${name}!</h1>`);
});

app.use((req, res, next) => {
res.status(404).sendFile(path.join(__dirname, 'public', '404.html'));
});

app.use((err, req, res, next) => {
console.error('Error encountered:', err);
res.status(500).json({ error: 'An internal server error occurred' });
});

server.listen(PORT, () => {
console.log(`Worker process ${process.pid} is running on port ${PORT}`);
});
}

创建一个 public 文件夹:

1
2
mkdir public
cd public

index.html

用作的首页的基本的 HTML 文件:

1
2
3
4
5
6
7
8
9
10
11
12
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Node.js Server</title>
</head>
<body>
<h1>Welcome to the node.js Server!</h1>
<p>This server is a simple server.</p>
</body>
</html>

404.html

1
2
3
4
5
6
7
8
9
10
11
12
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>404 - Page Not Found</title>
</head>
<body>
<h1>404 - Page Not Found</h1>
<p>The page you are looking for doesn't exist in this universe.</p>
</body>
</html>

启动服务器

1
node server.js

测试服务器功能

最终目录:

1
2
3
4
5
node-server/
├── public/
│ ├── index.html
│ ├── 404.html
├── server.js

一切就绪

你已经在你的设备创建并运行一个简单的 Node.js 服务器!这是学习后端开发基础知识以及了解服务器如何工作的好方法。