最近我在尝试从 C# 中的代码运行 nodejs 包时遇到了一个问题。
首先我在命令行安装了一个包(注释是针对不熟悉nodejs的人)
// npm as the node package manager
// -g means "install globally"
// quicktype is the package that i'm trying to use, though it doesn't matter here which package you want to try with
npm install -g quicktype
普通的命令行调用:
// a simple usage of quicktype's functionality
quicktype --version
这是我尝试复制命令行调用的尝试:
var startinfo = new ProcessStartInfo();
proc.StartInfo.FileName = "quicktype";
proc.StartInfo.Arguments = "--version";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.Start ();
执行失败,错误是:系统找不到指定的文件。
我能理解为什么它找不到程序,但仍然不知道如何正确定位。
我用 C# 编写了一个简单的 NodeJsServer
类,可以帮助您完成这些事情。它可以在 GitHub 上找到 here .它有很多选项,你可以在特定目录中执行'npm install'命令,或者启动NodeJs,检查当前状态(是否正在运行,是否正在编译,是否正在启动,是否正在安装),最后停止NodeJs。检查quick example usage .
这是您要执行的操作的原始代码(主要从 NodeJsServer
类复制):
// create the command-line process
var cmdProcess = new Process
{
StartInfo =
{
FileName = "cmd.exe",
UseShellExecute = false,
CreateNoWindow = true, // this is probably optional
ErrorDialog = false, // this is probably optional
RedirectStandardOutput = true,
RedirectStandardInput = true
}
};
// register for the output (for reading the output)
cmdProcess.OutputDataReceived += (object sender, DataReceivedEventArgs e) =>
{
string output = e.Data;
// inspect the output text here ...
};
// start the cmd process
cmdProcess.Start();
cmdProcess.BeginOutputReadLine();
// execute your command
cmdProcess.StandardInput.WriteLine("quicktype --version");
我是一名优秀的程序员,十分优秀!