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);
}
}
}
@jgwill
Copy link

jgwill commented Oct 15, 2018

Great, exactly what I needed to start my experimentation.
I want to use the output of the Node.JS, transform it into .net event...
I feel that will greatly help
Thanks

@JeremyTCD
Copy link

We've built an open source library that does this, Jering.Javascript.NodeJS:

string javascriptModule = @"
module.exports = (callback, x, y) => {  // Module must export a function that takes a callback as its first parameter
    var result = x + y; // Your javascript logic
    callback(null /* If an error occurred, provide an error object or message */, result); // Call the callback when you're done.
}";

// Invoke javascript
int result = await StaticNodeJSService.InvokeFromStringAsync<int>(javascriptModule, args: new object[] { 3, 5 });

// result == 8
Assert.Equal(8, result);

It keeps a Node.js process alive, allowing you to invoke javascript multiple times without starting lots of processes.

@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