1. 安装Node.js环境
在Debian系统上,推荐通过NodeSource仓库安装最新稳定版Node.js(支持长期维护),避免默认仓库版本过旧。具体步骤如下:
curl -fsSL https://deb.nodesource.com/setup_16.x | sudo -E bash -
sudo apt-get install -y nodejs
node -v # 查看Node.js版本(如v16.x.x)
npm -v # 查看npm版本(如8.x.x)
2. 编写自动化运维脚本
利用Node.js内置模块(如fs文件系统、child_process执行系统命令)或第三方模块(如axios HTTP请求、cron定时任务)编写脚本,覆盖常见运维场景:
const fs = require('fs');
const path = require('path');
const dirPath = path.join(__dirname, 'logs');
const filePath = path.join(dirPath, 'app.log');
fs.mkdirSync(dirPath, { recursive: true }); // 递归创建目录
fs.writeFileSync(filePath, 'Log initialized at ' + new Date()); // 写入初始日志
const { exec } = require('child_process');
exec('tar -czf /backups/app_$(date +%F).tar.gz /var/www/app', (error, stdout, stderr) => {
if (error) console.error(`Backup failed: ${error.message}`);
else console.log(`Backup completed: ${stdout}`);
});
cron模块设置周期性任务(如每小时采集系统指标)。const cron = require('cron');
const job = new cron.CronJob('0 * * * *', () => { // 每小时整点执行
const cpuUsage = process.cpuUsage();
console.log(`Hourly CPU usage: ${JSON.stringify(cpuUsage)}`);
});
job.start();
3. 运行与管理脚本
node /path/to/script.js
sudo npm install -g pm2
pm2 start /path/to/script.js --name "my-automation"
pm2 list # 查看所有进程状态
pm2 logs # 查看实时日志
pm2 restart my-automation # 重启进程
pm2 save # 保存当前进程列表(防止重启丢失)
4. 设置开机自启动
通过systemd服务或PM2的内置功能实现脚本开机自动运行:
/etc/systemd/system/node-automation.service):[Unit]
Description=Node.js Automation Script
After=network.target
[Service]
ExecStart=/usr/bin/node /path/to/script.js
Restart=always
User=your-username # 替换为实际用户
WorkingDirectory=/path/to/script # 脚本所在目录
[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl enable node-automation.service
sudo systemctl start node-automation.service
pm2 startup # 生成开机启动命令(根据提示执行)
pm2 save # 保存当前进程列表
5. 结合其他工具增强能力
const { exec } = require('child_process');
const playbookPath = '/path/to/deploy.yml';
exec(`ansible-playbook ${playbookPath}`, (error, stdout, stderr) => {
if (error) console.error(`Ansible execution failed: ${error.message}`);
else console.log(`Deployment result: ${stdout}`);
});
winston模块记录结构化日志,结合Prometheus+Grafana监控脚本运行状态;或通过PM2内置的监控面板(pm2 monit)查看CPU、内存占用。注意事项
.env文件+dotenv模块)管理。try-catch或回调函数的error参数,避免未捕获异常导致进程退出。pm2-logrotate模块或logrotate系统工具,防止日志文件过大占用磁盘空间。