Reputation: 255
Recently I've encountered a problem when trying to run a nodejs package from code in C#.
First I installed a package in command line (the comment is for people who are not familiar with 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
The normal command-line call:
// a simple usage of quicktype's functionality
quicktype --version
And here is my attempt to replicate the command-line call:
var startinfo = new ProcessStartInfo();
proc.StartInfo.FileName = "quicktype";
proc.StartInfo.Arguments = "--version";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.Start ();
It failed to execute, the error was : system cannot find the file specified.
I can understand why it couldn't locate the program but still cant figure out how to do it properly.
Upvotes: 6
Views: 3900
Reputation: 2857
I have written a simple NodeJsServer
class in C# that can help you with these things. It is available on GitHub here. It has a lot of options, you can execute 'npm install' commands in specific directories, or start NodeJs, check the current status (is it running, is it compiling, is it starting, is it installing) and finally stop the NodeJs. Check the quick example usage.
This is the raw code (copied mostly from the NodeJsServer
class) of what you are trying to do:
// 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");
Upvotes: 4