可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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.