在Linux系统上配置Node.js可以通过多种方式进行,以下是一些常见的技巧和步骤:
更新系统包:
sudo apt update
安装NodeSource库:
curl -fsSL https://deb.nodesource.com/setup_16.x | sudo -E bash -
安装Node.js和npm:
sudo apt install -y nodejs
验证安装:
node -v
npm -v
安装NVM:
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash
加载NVM:
source ~/.bashrc
安装Node.js:
nvm install node
使用特定版本:
nvm use 14
编辑配置文件:
打开~/.bashrc
或~/.zshrc
文件,添加以下内容:
export PATH=$PATH:/usr/local/node/bin
使环境变量生效:
source ~/.bashrc
Promise
和async/await
替代回调函数。使用HTTPS协议:
const https = require('https');
const fs = require('fs');
const privateKey = fs.readFileSync('path/to/private-key.pem', 'utf8');
const certificate = fs.readFileSync('path/to/certificate.pem', 'utf8');
const ca = fs.readFileSync('path/to/ca.pem', 'utf8');
const credentials = { key: privateKey, cert: certificate, ca: ca };
const app = express();
app.get('/', (req, res) => { res.send('Hello World!'); });
const httpsServer = https.createServer(credentials, app);
httpsServer.listen(443, () => console.log('HTTPS server listening on port 443'));
限制访问IP地址:
const allowedIps = ['192.168.1.100', '192.168.1.101'];
app.use((req, res, next) => {
const clientIp = req.connection.remoteAddress;
if (allowedIps.includes(clientIp)) { next(); } else { res.status(403).send('Access denied'); }
});
以上就是在Linux系统上配置Node.js的一些技巧和步骤,希望对你有所帮助。