0

我目前正在使用 node 命令来运行一些预制脚本。现在这是我在 Git 中输入的内容:

节点文件1.js

节点文件2.js

节点文件3.js

在输入下一个“node file.js”之前,我必须等待每个完成

有没有办法对文件夹中的所有文件执行此操作,而不是一个接一个地键入它们?谢谢!

4

2 回答 2

0

您可以使用fs.readdir首先获取当前目录中的所有文件

const fs = require('fs')
const files = fs.readdirSync('.')

然后过滤掉.js文件:

const jsFiles = files.filter(f => f.endsWith('.js'))

使用child_process一个一个地执行它们:

const { spawnSync } = require('child_process')
for (const file of jsFiles) {
  spawnSync('node', [file], { shell: true, stdio: 'inherit' })
}

我正在使用spawnSync它来同步执行文件(一个接一个)。

于 2020-08-11T15:57:30.437 回答
-1

您可以使用exec()函数通过 Javascript 运行命令。file1.js将这行代码插入到执行结束时调用函数的顶部,exec()依此类推。


例子

index.js

const { exec } = require("child_process");

exec("dir", (error, stdout, stderr) => {
    if (error) {
        console.log(`error: ${error.message}`);
        return;
    }
    if (stderr) {
        console.log(`stderr: ${stderr}`);
        return;
    }
    console.log(`stdout: ${stdout}`);
});

的输出node index.js

stdout:  Volume in drive C is Windows 10
 Volume Serial Number is 3457-05DE

 Directory of C:\dev\node

10.08.2020  20:52    <DIR>          .
10.08.2020  20:52    <DIR>          ..
10.08.2020  20:52    <DIR>          .vscode
10.08.2020  21:39               310 index.js
10.08.2020  21:15               239 package.json
               2 File(s)            549 bytes
于 2020-08-10T18:46:30.177 回答