linux上运行js脚本

貌似学运维,啥都要懂一点儿??????

我们将使用 Node.jsES6 模块语法。

首先,确保你已经安装了 Node.js。

创建项目文件结构

假设我们的项目结构如下:

复制代码
my_project/
├── index.js
└── math.js

1. 创建 math.js

math.js 文件中,定义一些导出的函数:

javascript 复制代码
// math.js

export function add(a, b) {
  return a + b;
}

export function subtract(a, b) {
  return a - b;
}

2. 创建 index.js

index.js 文件中,使用 import 语句导入 math.js 中的函数,并使用这些函数:

javascript 复制代码
// index.js

import { add, subtract } from './math.js';

const a = 5;
const b = 3;

console.log(`The sum of ${a} and ${b} is ${add(a, b)}`);
console.log(`The difference between ${a} and ${b} is ${subtract(a, b)}`);

3. 运行脚本

为了让 Node.js 支持 ES6 模块语法,你需要在 package.json 文件中添加 "type": "module",或者使用 .mjs 扩展名来命名你的文件。

方法1:使用 package.json

创建一个 package.json 文件:

json 复制代码
{
  "type": "module"
}

然后在终端中导航到 my_project 目录并运行脚本:

sh 复制代码
node index.js
方法2:使用 .mjs 扩展名

将文件名改为 index.mjsmath.mjs,然后直接运行:

sh 复制代码
node index.mjs

完整代码示例

math.js
javascript 复制代码
// math.js

export function add(a, b) {
  return a + b;
}

export function subtract(a, b) {
  return a - b;
}
index.js
javascript 复制代码
// index.js

import { add, subtract } from './math.js';

const a = 5;
const b = 3;

console.log(`The sum of ${a} and ${b} is ${add(a, b)}`);
console.log(`The difference between ${a} and ${b} is ${subtract(a, b)}`);

运行 node index.js,你将会看到以下输出:

复制代码
The sum of 5 and 3 is 8
The difference between 5 and 3 is 2
相关推荐
就叫飞六吧16 分钟前
TOML vs YAML:为什么 Cargo 选择 TOML?
linux·运维·服务器
MiNG MENS16 分钟前
nginx 代理 redis
运维·redis·nginx
IMPYLH30 分钟前
Linux 的 test 命令
linux·运维·服务器·chrome·bash
xrui581 小时前
2026实战:深度解析 Gemini 3.1 镜像站函数调用在自动化运维工单中的应用
linux·服务器·网络
HackTwoHub1 小时前
Linux 内核史诗级本地提权 全网深度复现、原理完整分析( CVE-2026-31431)
linux·运维·安全·web安全·网络安全·代码审计·安全架构
不可能的是1 小时前
Claude Code 子 Agent 机制全解:怎么跑起来、怎么被管理、怎么互不干扰
javascript
她说彩礼65万2 小时前
C语言 文件
linux·服务器·c语言
HSunR2 小时前
dify 搭建ai作业批改流
开发语言·前端·javascript
txg6662 小时前
自动驾驶领域热点简报(2026-04-26 ~ 2026-05-03)
linux·人工智能·自动驾驶
代码不加糖2 小时前
2026 跨境电商独立站实战:从 0 到 1 搭建高转化 SaaS 商城(附源码)
开发语言·前端·javascript