linux上运行js脚本

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

我们将使用 Node.js 和 ES6 模块语法。

首先,确保你已经安装了 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.mjs 和 math.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
相关推荐
默_笙3 小时前
🚓 分诊台与拆题术:让 RAG 学会判断和规划
前端·javascript
呃呃呃呃ex3 小时前
10. 现代前端工程化:ES6 React 项目实战与原理解析
前端·javascript
律宏阔3 小时前
WSL Docker 端口明明空闲,但就是绑不上端口
linux·windows
浪遏3 小时前
D2C 系统架构复盘:从设计稿到代码,我们踩过的坑和最终方案
前端·javascript·后端
律宏阔3 小时前
WSL 突然断网,无法 ping 内网或外网
linux·windows
穷人小水滴3 小时前
用容器编译 VirtualBox 虚拟机软件 (ArchLinux, podman)
linux·容器·virtualbox
Blanche15003 小时前
Webpack 构建流程解析
javascript·面试
Flynt3 小时前
官方说一个破折号拖慢整段高亮,我在 Node 里验证了一遍:机制是真的,2.8 倍没跑出来
javascript·性能优化·v8
默_笙4 小时前
🚗 把小说装进数据库了:我的第一个 RAG,和它的五个硬伤
前端·javascript
像我这样帅的人丶你还4 小时前
📱iPhone Duo 开屏动画咋实现的?
javascript·webgl·three.js