0

I need to execute some js files one after another, those js files are printing important information in the console.log.

I'm currently trying to use the following code, but it is not showing the console.log for sub js files.

How can I get this approach to work?

const fs = require('fs')
const exec = require('child_process').exec
const async = require('async') // npm install async
const path = require('path');


const scriptsFolder = path.resolve("./") + "\\" named scripts


const files = fs.readdirSync(scriptsFolder) 

const targetFiles = files.filter(function (file) {
    return path.extname(file).toLowerCase() === '.js';
});

const funcs = targetFiles.map(function (file) {
    return exec.bind(null, `node ${scriptsFolder}${file}`)

})

function getResults(err, data) {

    if (err) {
        return console.log(err)
    }
    const results = data.map(function (lines) {
        return lines.join('') 
    })
    console.log(results)
}

  async.series(funcs, getResults)
Hatem Husam
  • 177
  • 1
  • 3
  • 14

3 Answers3

1

As there is no interaction between the js files, I just use a batch script to run all of them sequentially as below

for /R %%f in (*.js) do if not %%f==%~dpnx0 node "%%f"
Hatem Husam
  • 177
  • 1
  • 3
  • 14
0

Why do you execute each js file in seperate process?

Try to require the files one after the other, with no child_process

Check this answer for great example of dynamic require of folder.

yeya
  • 1,968
  • 1
  • 21
  • 31
  • Thank you @yeya, because each js file is having a certain task to do & those js files are may increase / decrease depends on a regular basis. – Hatem Husam Mar 27 '19 at 06:48
  • If all you need is to run the scripts, and no need of interaction between them or with the output, you can run it with bash or batch script one by one – yeya Mar 27 '19 at 07:06
  • Thank you @yeya, any idea how to do that with a batch script as I'm running in Windows OS? – Hatem Husam Mar 27 '19 at 09:08
0

You can consider running the scripts using execSync and use the stdio: "inherit" option to direct output form each script to the parent process:

const files = fs.readdirSync(scriptsFolder)

const targetFiles = files.filter(function (file) {
    return path.extname(file).toLowerCase() === '.js';
});

for (let file of targetFiles) {
    execSync(`node ${scriptsFolder}/${file}`, {
        stdio: 'inherit'
    });
}
OzW
  • 848
  • 1
  • 11
  • 24