Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

nodejs run custom script before main script

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

+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?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading