user4329409
user4329409

Reputation: 23

How to execute the command NPM init in the nodejs file

How to execute the command npm init in the nodejs file? I want to use node. / index.js to execute the command. But what should I do if the command interacts with the user?

This code is directly stuck, and the subsequent question and answer cannot be carried out.I hope users can fill in the information normally

let exec = require('child_process').exec;
exec("npm init")

Upvotes: 1

Views: 1574

Answers (2)

RobC
RobC

Reputation: 24952

To allow users to fill in the questionnaire via the CLI, consider using the child_process module's spawn() method instead of exec().

*Nix (Linux, macOS, ... )

For example:

index.js

const spawn = require('child_process').spawn;

spawn('npm', ['init'], {
  shell: true,
  stdio: 'inherit'
});

Note: After the user has completed the questionnaire this example (above) creates the resultant package.json file in the current working directory, i.e. the same directory from where the node command invoked index.js.

However, If you want to ensure that package.json is always created in the same directory as where index.js resides then set the value of the cwd option to __dirname. For example:

const spawn = require('child_process').spawn;

spawn('npm', ['init'], {
  cwd: __dirname,        // <--- 
  shell: true,
  stdio: 'inherit'
});

Windows

If you are running node.js on Windows then you need to use the following variation instead:

script.js

const spawn = require('child_process').spawn;

spawn('cmd', ['/c', 'npm init'], {  //<----
  shell: true,
  stdio: 'inherit'
});

This also utilizes the spawn() method, however it starts a new instance of Windows command shell (cmd). The /c option runs the npm init command and then terminates.


Cross-platform (Linux, macOS, Windows, ... )

For a cross platform solution, (i.e. one that runs on Windows, Linux, macOS), then consider combining the previous examples to produce the following variation:

script.js

const spawn = require('child_process').spawn;

const isWindows = process.platform === 'win32';
const cmd = isWindows ? 'cmd' : 'npm';
const args = isWindows ? ['/c', 'npm init'] : ['init'];

spawn(cmd, args, {
  shell: true,
  stdio: 'inherit'
});

Upvotes: 1

Jan
Jan

Reputation: 1

Assuming there doesn't need to be any user input you could do:

let exec = require('child_process').exec;
exec("npm init -y")

Upvotes: 0

Related Questions