在 Ubuntu 上使用 Node.js 写脚本,一般步骤如下:
sudo apt update
sudo apt install nodejs npm
查看版本:
node -v
npm -v
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt install -y nodejs
新建一个文件,例如 hello.js:
nano hello.js
写入内容:
console.log("Hello Ubuntu from Node.js");
保存后运行:
node hello.js
// args.js
console.log(process.argv);
运行:
node args.js a b c
输出:
[ '/usr/bin/node', '/path/args.js', 'a', 'b', 'c' ]
#!/usr/bin/env node
console.log("This is a node script");
chmod +x hello.js
./hello.js
(可选)放到 /usr/local/bin:
sudo cp hello.js /usr/local/bin/hello
sudo chmod +x /usr/local/bin/hello
hello
const fs = require('fs');
const data = fs.readFileSync('test.txt', 'utf8');
console.log(data);
const { execSync } = require('child_process');
console.log(execSync('ls -l').toString());
文件命名为 script.mjs:
import fs from 'fs';
console.log(fs.readdirSync('.'));
运行:
node script.mjs
npm init -y
安装第三方库:
npm install axios
如果你有具体需求(比如定时任务、文件处理、接口请求、系统运维脚本),可以告诉我,我可以直接帮你写示例。