0

My folder structure:

app

  Model

    user.js
    post.js

My package.json file

"scripts": {
    "migrate": "node ./app/Model/"
}

I want to run javascript file in command line dynamically.

Like:

npm run migrate user.js
npm run migrate post.js

Is there any way to achieve this?

2 Answers 2

1

You could write a script that dynamically requires the decired js file.

"scripts": {
    "migrate": "node model.js"
}

Then model.js like this:

const path = require('path');    
require(path.join(__dirname, 'app', 'Model', process.argv[2]));
Sign up to request clarification or add additional context in comments.

3 Comments

It's giving Error: Cannot find module 'E:\project\app\Model\C:\Program Files\nodejs\node.exe'
@ShivamChhetri I don't have node on my current machine. So i cant test it. But it looks like the first argument in process.argv is a ref to node. try process.argv[1] instead. And remember the --
It's working with process.argv[2] and there's no need of -- before user.js
0
"scripts": {
"migration": "node Model.js"

}

const program = require('commander');

program
    .command('f <file>')
    .description('Database migration.')
    .action(async (file) => {
        console.log(file);//do something here
    });


program.parse(process.argv);

npm run migration f post.js

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.