从c#控制台应用程序运行npm init
我已经尝试从C#控制台应用程序运行“npm init”命令,使用以下代码:
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");
但没有发生。 运行我的应用程序后,我只有2个空行。 请帮忙解决这个问题。
看看我运行npm run dist
命令的例子。
var psiNpmRunDist = new ProcessStartInfo { FileName = "cmd", RedirectStandardInput = true, WorkingDirectory = guiProjectDirectory }; var pNpmRunDist = Process.Start(psiNpmRunDist); pNpmRunDist.StandardInput.WriteLine("npm run dist & exit"); pNpmRunDist.WaitForExit();
您需要捕获Process.StandardOutput: ProcessStartInfo.RedirectStandardOutput
喜欢这个:
p.Start(); // To avoid deadlocks, always read the output stream first and then wait. string output = p.StandardOutput.ReadToEnd(); p.WaitForExit();
尽pipe由于NPM可能是一个长时间运行的过程,因此您可能需要连接一个事件处理程序(如以下样本): 使用进程的实时控制台输出redirect
我已经解决了这个问题:
foreach (string s in commands) { proc = Process.Start("npm.cmd", s); proc.WaitForExit(); }
npm init
会提示新项目上的多个用户input。 例如,项目名称,版本,作者等。这些值在StandardInput
上预期。 您正确redirectStandardInput
,但我看不到您在这里提供这些值。 NPM将阻塞,直到它收到这个input,这可能是你看到应用程序冻结的原因。 您需要使用WriteLine
来为NPM的问题提供答案,以便向前推进,或者至less为每个问题填写空白的WriteLine
就足够了。 你可以通过调用p.StandardInput.WriteLine
来做到这p.StandardInput.WriteLine
。
在我的NPM(3.8.6)版本中,有如下问题:
name: (foo) version: (1.0.0) description: entry point: (index.js) test command: git repository: keywords: author: license: (ISC)
除此之外,NPM会提示“你确定吗?” 最后。