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
相关推荐
总要学点什么9 分钟前
第105篇:三维特效-流动图片墙体效果——让箭头沿墙长滚,它俩竟是同一份代码
开发语言·javascript·ecmascript·gis·webgl·材质·cesium
科研邪修法35 分钟前
培训PDF保护配置:把需求转换成可验收权限
linux·服务器·网络
Felven1 小时前
中科驭数100G网卡RDMA性能测试
linux·rdma·中科驭数·100g网卡
分布式存储与RustFS2 小时前
镜像仓库的层别只堆本地盘:用 RustFS 给 Harbor 当 S3 后端
运维·云原生·开源·对象存储·分布式存储·s3·性能基准
Agent世界2 小时前
用 CDP 做发布自动化:四道机器闸门与产物验收
前端·javascript
总要学点什么2 小时前
第104篇:三维特效-流动墙体效果——让贴图沿墙流动,它却只肯走一条对角线
开发语言·javascript·ecmascript·gis·webgl·材质·cesium
程序员大阳2 小时前
副队长ES6+教程(3)--解构赋值
前端·javascript·es6·赋值·解构
神膘护体小月半2 小时前
css - 元素背景图由 hover 触发,初次加载时闪动的解决办法
前端·javascript·css
程序员大阳3 小时前
副队长ES6+教程(2)--let 与 const
前端·javascript·es6·const·let·var
雪落漂泊4 小时前
Liunux进程(七):程序控制篇(中)
linux·运维·windows