Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Start Node.js server from a C# Application

A requirement has arisen that I need to start a Node.js server from a C# application, this is as simple as running a server.js script within the Node.js console. However, I'm not entirely certain how exactly to achieve that.

Here's what I've looked into so far:

In the Node.js installation, there's a file called C:\Program Files (x86)\nodejs\nodevars.bat, this is the command prompt window for Node.js. To start the server, I could possibly be using the following steps:

  1. Execute the nodevars.bat file.
  2. SendKeys to the new process console window to start the server.

This approach feels a bit fragile. There's no guarantee that the target user will have their Node.js installation in the same place, also sending keys to a process may not be an ideal solution.

Another method could be:

  1. Write a batch file that executes nodevars.bat.
  2. Execute the batch file from the C# application.

This seems like a better approach. However, the only problem here is that the nodevars.bat opens in a new console window.

So to the question(s), is there a way I can start a node.js server script using functionality built into the node.js installation? Perhaps sending arguments to the node.exe?

like image 211
Mike Eason Avatar asked Jan 06 '16 09:01

Mike Eason


2 Answers

If it is to serve multiple users, i.e. as a server, then you can use the os-service package, and install a Windows service. You can then start and stop the service using the standard API.

If you are to start the server as a "single purpose" server, i.e. to serve only the current user, then os-service is the wrong approach. (Typically when using this approach you will specify a unique port for the service to use, which will only be used by your application).

To start a batch file or other Console application, from C#, without showing a console window, use the standard method, but be sure to specify:

ProcessStartInfo psi = new ProcessStartInfo();
psi.UseShellExecute = false;   // This is important
psi.CreateNoWindow = true;     // This is what hides the command window.
psi.FileName = @"c:\Path\to\your\batchfile.cmd";
psi.Arguments = @"-any -arguments -go Here";   // Probably you will pass the port number here
using(var process = Process.Start(psi)){
    // Do something with process if you want.
}
like image 118
Ben Avatar answered Oct 16 '22 16:10

Ben


There are a few different ones but I recommend the os-service package.

like image 24
mrvautin Avatar answered Oct 16 '22 17:10

mrvautin