1

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?

1 Answer 1

4

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

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

and execute with

npm start

again

Sign up to request clarification or add additional context in comments.

1 Comment

Tested now "start": "node index.js", "prestart": "node ../my_dir/my_script.js" with npm start AND IT WORK! Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.