如何从目录运行(同步)多个.js文件

时间:2018-09-30 22:38:34

标签: javascript node.js synchronization

我正在尝试从目录中运行多个.js文件:

exampleDir / test.js

console.log('hi');

run.js

const fs = require('fs');
const {execFileSync} = require('child_process');

const testsFolder = './exampleDir/';

const files = fs.readdirSync(testsFolder);

const funcs = files.map(function(file) {
    const out = execFileSync(`node ${testsFolder}${file}`);
    console.log(out.toString());
});

但是我得到了

> example@1.0.0 test /home/perdugames/example
> node ./run.js

child_process.js:624
    throw err;
    ^

Error: spawnSync node ./exampleDir/test.js ENOENT
  ...

1 个答案:

答案 0 :(得分:0)

应明确指定文件路径,最好独立于当前工作目录并相对于当前模块。要创建新的Node进程,spawn中有spawnSyncchild_process

...
const path = require('path');
const testsFolder = path.join(__dirname, './exampleDir/');
const files = fs.readdirSync(testsFolder);

const funcs = files.map(function(file) {
    const filePath = path.join(testsFolder, file);
    const out = spawnSync(filePath);
    console.log(out.stdout.toString());
});