温馨提示×

ubuntu怎么用nodejs写脚本

小樊
38
2026-08-31 22:26:00
栏目: 编程语言

在 Ubuntu 上使用 Node.js 写脚本,一般步骤如下:


一、安装 Node.js

方式 1:使用 apt(简单,版本可能较旧)

sudo apt update
sudo apt install nodejs npm

查看版本:

node -v
npm -v

方式 2:使用 NodeSource(推荐,版本新)

curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt install -y nodejs

二、创建 Node.js 脚本

新建一个文件,例如 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' ]

四、把脚本当作命令执行(像 shell 脚本)

1. 在文件第一行加 shebang

#!/usr/bin/env node
console.log("This is a node script");

2. 赋予执行权限

chmod +x hello.js

3. 直接运行

./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);

执行 shell 命令

const { execSync } = require('child_process');
console.log(execSync('ls -l').toString());

使用现代语法(ES Module)

文件命名为 script.mjs

import fs from 'fs';
console.log(fs.readdirSync('.'));

运行:

node script.mjs

六、初始化项目(可选)

npm init -y

安装第三方库:

npm install axios

如果你有具体需求(比如定时任务、文件处理、接口请求、系统运维脚本),可以告诉我,我可以直接帮你写示例。

0