0

Strange question, but currently I have a script that I run from the terminal which requires a parameter. Normally I will run this by doing node script.js param, but now I want to run this script with the parameter from inside a JS file when the Express server loads.

The parameter is taken in and defined in the file like this:

var param = process.argv[process.argv.length - 1];

What is the best practice for making this file accessible elsewhere in my Node app and running it?

1
  • require("script.js") file from other file? Commented Jul 15, 2016 at 5:40

2 Answers 2

1

If I understand you correctly following should work.

script.js

module.exports = function (params) {

console.log(params);

}

main.js

var param = process.argv[process.argv.length - 1];

require('./script')(param);
Sign up to request clarification or add additional context in comments.

Comments

1

If you need to get param from another source when the script is required you can make a verification if the script is running directly from command line or it was required:

if (require.main === module) {
    var param = process.argv[process.argv.length - 1];
} else {
    var param = // get from other source. 
}

Comments

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.