从C#控制台应用程序运行npm init

8
我尝试从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");

但是什么都没有发生。在运行我的应用程序后,我只得到了两个空白行。请帮助解决这个问题。

5个回答

9

看一下我运行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();

我收到了来自@stefan.seeland的编辑建议,并附有评论:“在没有设置UseShellExecute的情况下会抛出'System.InvalidOperationException'”。它已被其他两个用户拒绝。我正在使用.NET Core 1.1,但我没有遇到这个异常。是否有人在.NET Framework或其他Core版本中没有使用UseShellExecute而遇到了这个异常,甚至(但我怀疑)在这个版本中? - nopara73

4
以下内容适用于我:

以下是我使用的方法:

private static string RunCommand(string commandToRun, string workingDirectory = null)
{
    if (string.IsNullOrEmpty(workingDirectory))
    {
        workingDirectory = Directory.GetDirectoryRoot(Directory.GetCurrentDirectory());
    }

    var processStartInfo = new ProcessStartInfo()
    {
        FileName = "cmd",
        RedirectStandardOutput = true,
        RedirectStandardInput = true,
        WorkingDirectory = workingDirectory
    };

    var process = Process.Start(processStartInfo);

    if (process == null)
    {
        throw new Exception("Process should not be null.");
    }

    process.StandardInput.WriteLine($"{commandToRun} & exit");
    process.WaitForExit();

    var output = process.StandardOutput.ReadToEnd();
    return output;
}

你可以这样使用它:

var initResult = RunCommand("npm run init", @"E:\Work\");

这同样适用于dotnet core和标准的.net框架。


3
我是这样解决这个问题的:

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

1

在“output”变量中是否填充了任何内容? - denvercoder9
'output' 变量为空。实际上,进程在 p.Start() 代码处被冻结。 - Nisu

0

npm init 在新项目上提示用户输入几个参数,例如项目名称、版本、作者等。这些值应该在 StandardInput 上提供。您已经正确地重定向了 StandardInput,但我没有看到您在此处提供这些值。NPM 将阻塞直到它接收到此输入,这可能是您看到应用程序冻结的原因。您需要使用 WriteLine 来提供 NPM 问题的答案以继续前进,或者至少对于每个问题一个空白的 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 在最后会提示“你确定吗?”。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接