繁体   English   中英

如何在nodejs文件中执行命令NPM init

[英]How to execute the command NPM init in the nodejs file

如何在nodejs文件中执行命令npm init 我想使用node. / index.js node. / index.js执行命令。 但是如果命令与用户交互,我该怎么办?

这段代码直接卡死了,无法进行后续问答。希望用户能正常填写信息

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

假设您不需要任何用户输入:

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

要允许用户通过 CLI 填写问卷,请考虑使用child_process模块的spawn()方法而不是exec()

*尼克斯(Linux,macOS,...)

例如:

index.js

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

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

注意:在用户完成调查问卷后,此示例(上图)在当前工作目录(即node命令调用index.js的同一目录)中创建生成的package.json文件。

但是,如果要确保package.json始终创建在与index.js所在的目录相同的目录中,则将cwd选项的值设置为__dirname 例如:

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

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

Windows

如果您在 Windows 上运行 node.js,那么您需要使用以下变体:

脚本.js

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

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

这也使用了spawn()方法,但是它启动了 Windows 命令 shell ( cmd ) 的新实例。 /c选项运行npm init命令,然后终止。


跨平台(Linux、macOS、Windows、...)

对于跨平台解决方案(即在 Windows、Linux、macOS 上运行的解决方案),然后考虑结合前面的示例以产生以下变体:

脚本.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'
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM