Skip to content

Instantly share code, notes, and snippets.

@elerch
Last active September 9, 2023 13:43
Show Gist options
  • Save elerch/5628117 to your computer and use it in GitHub Desktop.
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…
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);
}
}
}
@ppaska
Copy link

ppaska commented Feb 5, 2021

Same way running Python code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment