Run npm init from the c# console app

匿名 (未验证) 提交于 2019-12-03 01:23:02

问题:

I have try to run "npm init" command from the c# console app, using this code:

private void Execute(string command, string arg)     {         Process p = new Process();         p.StartInfo.FileName = command;         p.StartInfo.Arguments = arg;         p.StartInfo.UseShellExecute = false;         p.StartInfo.RedirectStandardOutput = true;         p.StartInfo.RedirectStandardInput = true;         p.StartInfo.WorkingDirectory = @"E:\Work\";           p.Start();         p.WaitForExit();     }      Execute(@"C:\Program Files\nodejs\npm.cmd", "init"); 

But nothing happening. I getting only 2 empty lines after the running my app. Please, help to resolve this problem.

回答1:

Take a look at my example of running the npm run dist command.

var psiNpmRunDist = new ProcessStartInfo {     FileName = "cmd",     RedirectStandardInput = true,     WorkingDirectory = guiProjectDirectory }; var pNpmRunDist = Process.Start(psiNpmRunDist); pNpmRunDist.StandardInput.WriteLine("npm run dist & exit"); pNpmRunDist.WaitForExit(); 


回答2:

You'll need to capture the Process.StandardOutput: ProcessStartInfo.RedirectStandardOutput

Like this:

p.Start();  // To avoid deadlocks, always read the output stream first and then wait. string output = p.StandardOutput.ReadToEnd(); p.WaitForExit(); 

Although, since NPM can be a long running process, you may want to wire up an event handler like in these samples: Realtime Console Output Redirection using Process



回答3:

I have resolved this problem like this:

foreach (string s in commands) {    proc = Process.Start("npm.cmd", s);    proc.WaitForExit(); } 


回答4:

npm init prompts for several user inputs on a new project. For example, the project name, version, author, etc. These values are expected on StandardInput. You are correctly redirecting StandardInput, but I do not see you providing these values here. NPM will block until it receives this input, which is likely why you are seeing the application freeze. You will need to use WriteLine to provide the answers to NPM's questions in order to move forward, or at a minimum a blank WriteLine for each question will suffice. You can do this by calling p.StandardInput.WriteLine.

On my version of NPM (3.8.6), the following questions are asked:

name: (foo)  version: (1.0.0)  description:  entry point: (index.js)  test command:  git repository:  keywords:  author:  license: (ISC) 

In addition to this, NPM will prompt with an "Are you sure?" at the end.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!