Home > Enterprise >  nodejs run custom script before main script
nodejs run custom script before main script

Time:12-01

I want to run ../my_dir/my_script.js each time when I run node index.js from actual app project folder.

In others words, I need my_script.js to be common in every app (A,B,C...N) and executing before index.js

Structure:

 my_dir
  -my_script.js
 appA
   node_modules
  -package.json
  -index.js
 appB
   node_modules
  -package.json
  -index.js

my_script.js

console.log('my_script.js from parent directory STARTED');

package.json (similar for each appA, appB ... etc)

{
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    //I HAVE TRIED
    "start": "node ../my_dir/my_script.js",
    "postinstall": "npm run-script ../my_dir/my_script.js",
    "preinstall": "npm run --prefix ../my_dir/my_script.js",
    
  }
}

index.js (similar for each appA, appB ... etc);

console.log('index.js STARTED');

If I try inside appA node index.js I got index.js STARTED

If I try inside appA npm start I got my_script.js from parent directory STARTED

Expected: (running both):

my_script.js from parent directory STARTED
index.js STARTED

Any idea how to achieve that?

CodePudding user response:

I don't think it is possible to automatically have a second script run when using the command line node command. What you can do is either run both scripts manually

node ../my_dir/my_script.js && node index.js

or bundle them in your package.json

"start": "node ../my_dir/my_script.js && node index.js",

and execute with

npm start

Your postinstall and preinstall are not quite right, those get run when doing npm install (you can put the post and pre keywords before any command https://docs.npmjs.com/cli/v9/using-npm/scripts)

so you could also do (untested)

"start": "node index.js",
"prestart": "node  ../my_dir/my_script.js"

and execute with

npm start

again

  • Related