Last active
September 9, 2023 13:43
-
-
Save elerch/5628117 to your computer and use it in GitHub Desktop.
Using C# to host and communicate with node.js This proof of concept launches node.exe as a separate process, redirecting stdin/stdout. It simply calculates 2+2, then sends a process.exit() call after 10 seconds so the (.Net) app can complete (the suppressOut just gets node to output "undefined" instead of the full return value of setTimeout). Da…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace ConsoleApplication1 | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var proc = new System.Diagnostics.Process(); | |
proc.StartInfo.CreateNoWindow = true; | |
proc.StartInfo.RedirectStandardInput = true; | |
proc.StartInfo.RedirectStandardOutput = true; | |
proc.StartInfo.UseShellExecute = false; | |
proc.StartInfo.RedirectStandardError = true; | |
proc.StartInfo.FileName = "node.exe"; | |
proc.StartInfo.Arguments = "-i"; | |
proc.Start(); | |
proc.BeginOutputReadLine(); | |
proc.StandardInput.WriteLine("2 + 2;"); | |
proc.StandardInput.WriteLine("setTimeout(function(){ process.exit();}, 10000).suppressOut;"); | |
proc.OutputDataReceived += proc_OutputDataReceived; | |
proc.WaitForExit(); | |
} | |
static void proc_OutputDataReceived(object sender, System.Diagnostics.DataReceivedEventArgs e) | |
{ | |
Console.WriteLine(e.Data); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
We've built an open source library that does this, Jering.Javascript.NodeJS:
It keeps a Node.js process alive, allowing you to invoke javascript multiple times without starting lots of processes.