linux上运行js脚本

貌似学运维,啥都要懂一点儿??????
我们将使用 Node.jsES6 模块语法。

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

创建项目文件结构

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

my_project/
├── index.js
└── math.js

1. 创建 math.js

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

// 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 中的函数,并使用这些函数:

// 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 文件:

{
  "type": "module"
}

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

node index.js
方法2:使用 .mjs 扩展名

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

node index.mjs

完整代码示例

math.js
// math.js

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

export function subtract(a, b) {
  return a - b;
}
index.js
// 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
  • 9
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

少陽君

谢谢老板的拿铁

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值