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
相关推荐
用户85249507184几秒前
Bun 到底是什么?一个比 Node.js "更快更香"的 JS 运行时
javascript·程序员
utf8mb4安全女神几秒前
【shell函数】【shell脚本】定期自动检查服务器磁盘使用情况并发出告警
运维·服务器
riuphan2 分钟前
JavaScript 事件循环:单线程异步编程的核心机制
前端·javascript
小小龙学IT5 分钟前
Midscene.js:AI驱动的跨平台UI自动化革命
javascript·人工智能·ui
Cx330❀5 分钟前
【MySQL基础】库与表的全面操纵指南
linux·服务器·网络·数据库·c++·mysql
凡人叶枫7 分钟前
Effective C++ 条款03:尽可能使用 const
linux·开发语言·c++·嵌入式开发
程序员佳佳10 分钟前
我在 Windows 和低配 Linux 上做 RAG:Milvus、FAISS、向量 API 中转的中立实测
linux·人工智能·windows·gpt·aigc·milvus·faiss
加成BUFF14 分钟前
第六天 ROS 《Action 通信实验》
linux·机器人·ros
ShineWinsu14 分钟前
对于Linux:进程信号的解析—下
linux·运维·服务器·面试·笔试·进程·信号
YIN_尹16 分钟前
【Linux系统编程】基础IO第二讲——文件描述符
android·linux·服务器