Skip to content

参数

process.argv 返回数组,第一个元素为 Node.js 启动路径,第二个元素为文件路径。

// temp.mjs

// 获取参数
const args = process.argv.slice(2);

// 检测参数
if (args.every(i => /^\d+$/.test(i)) === false) {
  console.log('参数错误。');
  process.exit(1);
}

const arr = [2, 4, 6, 8, 10].slice(...args);
console.log(arr);
node temp.mjs
node temp.mjs 1
node temp.mjs 1 3
node temp.mjs a b
[ 2, 4, 6, 8, 10 ]
[ 4, 6, 8, 10 ]
[ 4, 6 ]
参数错误。

联系 math@baima.site