By Alex

Node.cs

C# 1.53 KiB 18 19 days ago
using System.Diagnostics; namespace DevBin.Utils; public class Node { public static string RunScript(string scriptName, IDictionary<string, string>? env, string? input) { var process = new Process(); process.StartInfo.FileName = "node"; process.StartInfo.Arguments = scriptName; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardInput = true; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.StartInfo.WorkingDirectory = Path.Combine(Environment.CurrentDirectory, "Scripts"); if (env != null) { foreach (var (k, v) in env) { process.StartInfo.Environment[k] = v; } } process.OutputDataReceived += Process_OutputDataReceived; Console.WriteLine("Starting node"); process.Start(); process.StandardInput.WriteLine(input); process.WaitForExit(); Console.WriteLine("Node is done. Exit code: {0}. Took {1}s", process.ExitCode, process.TotalProcessorTime.TotalSeconds); if (process.HasExited && process.ExitCode != 0) { throw new Exception(process.StandardError.ReadToEnd()); } var output = process.StandardOutput.ReadToEnd(); return output; } private static void Process_OutputDataReceived(object sender, DataReceivedEventArgs e) { Console.WriteLine(e.Data); } }