arjunkm
arjunkm

Reputation: 479

Single Node script to run multiple Node scripts sequentially

I have multiple Node.js scripts (Ex: script1.js, script2.js, script3.js, etc.) that need to be executed in a specific sequence.

I'm trying to have a "master" (so to say) Node script that will lay out the execution order of these files (Ex: script1.js -> script2.js -> script3.js and so on). P.S - script1.js has to finish execution before script2.js can start and so on.

I tried executing a single Node script using "child_process" and it worked, need help with multiple files and in a specific sequence.

Thanks in advance!

Upvotes: 1

Views: 1984

Answers (4)

Hồng Phúc
Hồng Phúc

Reputation: 478

To easy to run multi scripts in a specific sequence, you should put all command into package.json at "scripts" part in that sequence. then you just need run one command in terminal to achieved it.

EX:
First, open package.json:

"scripts": {
    // ... some other scripts ...
    "runall": "node script1.js [params] && node script2.js [params] && node script3.js [params]]" // params is optional
  }

Second: open Terminal and type

npm run runall

Upvotes: 1

Rahul Sharma
Rahul Sharma

Reputation: 10071

If you are not doing any async operation in the file, it's load sequentially. otherwise, create another file and call the async function in that.

// script1.js
module.export.script1 = async () => {
    // some async code 
}

// script2.js
module.export.script2 = async () => {
    // some async code 
}

// script3.js
module.export.script3 = async () => {
    // some async code 
}

// index.js
const script1 = require('./script1.js');
const script2 = require('./script2.js');
const script3 = require('./script3.js');

async function name(params) {
    await script1();
    await script2();
    await script3();
}

Upvotes: 1

Jujubes
Jujubes

Reputation: 434

Create one file call it index.js

using index.js to either import or require the other files

i actually do this with all my routes in express js using express-enrouten.

 //index.js
 require('folder/one.js');
 require('folder/two.js');

 //folder/one.js -> express route format but you can be as creative as you want
 module.exports = function(req, res, next){
   //do some things

   //Go to next script
   next()
 }

Upvotes: 1

3rdsty4bl00d
3rdsty4bl00d

Reputation: 134

You have to set your parent Js file in a package.json file.

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon app.js"
  }

And then put your child components inside the app.js file according to the output you want.

Upvotes: 1

Related Questions