GithubHelp home page GithubHelp logo

jeringtech / javascript.nodejs Goto Github PK

View Code? Open in Web Editor NEW
444.0 444.0 43.0 1.69 MB

Invoke Javascript in NodeJS, from C#

License: Other

C# 95.03% TypeScript 4.60% JavaScript 0.37%
csharp dotnet javascript nodejs

javascript.nodejs's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

javascript.nodejs's Issues

Relative path for InvokeFromFileAsync

I am trying to have a relative path to my script file. I have a subfolder "NodeScripts" in a web folder that the app is running from. The script file is inside of NodeScripts. The command looks like this:
StaticNodeJSService.InvokeFromFileAsync("./NodeScripts/exportChart.js"

does not work. If I specify a full local path then it works.
Any idea?

Thanks

Example of returning a stream? Result.stream is undefined

I'm new to node.js streams, buffers and pipes.

I have a buffer that deserializes to:
{"type":"Buffer","data":[49,46,48,48,49,58,49,49,51,29,49,46,48,48,50,58,48,53,48,50,29,49,46,48,48,51,58,49,31,49,30,50,31,48,48,29,49,46,48,48,52

I would like to return it as a stream.

For example I have this index.js:
module.exports = function(result, ...

To return a stream I would have to do something like:

        var stream = require('stream');
        var bufferStream = new stream.PassThrough();
        bufferStream.end(f(message));
        bufferStream.pipe(result.stream)

This is my calling code:

 dynamic result2 = StaticNodeJSService
.InvokeFromFileAsync<Stream>(
@"...\index.js",
args: new[] { "..." }).Result;

however result.stream seems to be undefined, and I get an error:

'One or more errors occurred. (Cannot read property 'on' of undefined
TypeError: Cannot read property 'on' of undefined
    at PassThrough.Readable.pipe (_stream_readable.js:612:8)

What am I doing wrong? Why is result.stream null?

InvokeFromStringAsync cannot load modules from node_modules

https://nodejs.org/api/modules.html#modules_loading_from_node_modules_folders
InvokeFromFileAsync works perfectly fine if you try to load modules like this: require('jsdom'), so long as it follows the rules above. Since there is no script file when using InvokeFromStringAsync, you would think that require starts from NodeJS's working directory, like it does when running the cli. However, setting NodeJSProcessOptions.ProjectPath does not appear to have any effect and module.paths is undefined as well.

Strong name signing for assembly in NuGet package

Hello, Jeremy!

Could you please sign the Jering.Javascript.NodeJS.dll assembly.

You must first generate the *.snk file, and then add the following code to the *.csproj file:

<Project>
  …
  <PropertyGroup>
    …
    <AssemblyOriginatorKeyFile>PATH_TO_YOUR_KEY_FILE</AssemblyOriginatorKeyFile>
    <SignAssembly>true</SignAssembly>
    <PublicSign Condition=" '$(OS)' != 'Windows_NT' ">true</PublicSign>
    …
  </PropertyGroup>
  …
</Project>

Error installing latest stable version

I am trying adding a package version 5.4.4 and getting this:
Failed to add reference to 'System.Memory'.
Error HRESULT E_FAIL has been returned from a call to a COM component.

as a result the package is not installed. Any idea?

PhysicalFileProvider.Root and file not found issues in production build

My Node.js project lives under a Microservices folder within my .NET project. In development, doing something like this works fine:

services.AddNodeJS();
var physicalFileProvider = new PhysicalFileProvider(Directory.GetCurrentDirectory());
var projectPath = Path.Combine(physicalFileProvider.Root, "Microservices", "my-specific-node-js-microservice-folder");
services.Configure<NodeJSProcessOptions>(options => options.ProjectPath = projectPath);

and then, (since I use TypeScript and produce .js file artifacts - this is already done during the build stage, and I am sure that the file exists), the actual file to call is./dist/index.js:

return await nodeJSService.InvokeFromFileAsync<Generated>("./dist/index.js", args: new[] { generatorOptions.StateCode });

I've tried a variety of file paths now for my production build, even hardcoding the relative file path from the root of my machine to index.js. All various ways of specifying the path work fine in development, but none work on my production server. I always get:

[2] Refer to the InnerException for further details.
        ---> System.ComponentModel.Win32Exception (2): No such file or directory
          at System.Diagnostics.Process.ForkAndExecProcess(String filename, String[] argv, String[] envp, String cwd, Boolean redirectStdin, Boolean redirectStdout, Boolean redirectStderr, Boolean setCredentia>
          at System.Diagnostics.Process.StartCore(ProcessStartInfo startInfo)
          at System.Diagnostics.Process.Start()
          at System.Diagnostics.Process.Start(ProcessStartInfo startInfo)
          at Jering.Javascript.NodeJS.NodeJSProcessFactory.CreateProcess(ProcessStartInfo startInfo)
          --- End of inner exception stack trace ---
          at Jering.Javascript.NodeJS.NodeJSProcessFactory.CreateProcess(ProcessStartInfo startInfo)
          at Jering.Javascript.NodeJS.NodeJSProcessFactory.Create(String serverScript)
          at Jering.Javascript.NodeJS.OutOfProcessNodeJSService.CreateAndSetUpProcess(EventWaitHandle waitHandle)
          at Jering.Javascript.NodeJS.OutOfProcessNodeJSService.ConnectIfNotConnected()

No matter what path I specify, the package complains that it cannot find my index.js file. What's going wrong here? This may be unrelated to this package, but I've used PhysicalFileProvider and the Root value with many other projects and it has worked as expected. Is there some other setting I need to set other than options.ProjectPath? If it's helpful, my production server is an Ubuntu 21.04 instance.

I saw in this issue that one can use AppDomain.CurrentDomain.BaseDirectory instead of physicalFileProvider.Root as the root folder, but I don't deploy my Node.js project as an assembly - as I mentioned, it sits in its own Microservices folder in the .NET project root.

Any thoughts or ideas of what could be missing here?

Installing via NuGet in VS2019 with AspNetCore 2.1

There is a version conflict with AspNetCore.Hosting.Abstractions when trying to install NodeJS with the following combination:

  • Visual Studio 2019
  • AspNetCore 2.1.0

Visual Studio 2019 error message:
image

Here is the content of my csprog file:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp2.1</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <Folder Include="wwwroot\" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.App" />
  </ItemGroup>

</Project>

Here is the content of my global.json file:

{
  "sdk": {
    "version": "2.1.300"
  }
}

Note: I don't experience any of these problems once I upgrade to .Net Core 3.

Undefined type

Hello, Jeremy!

In Jering.Javascript.NodeJS values of null and undefined types are always returned as null, that causes inconvenience. Most JS engines for .NET has a clearly separation for null and undefined types. As a rule, to represent undefined in .NET is used a custom type (see as examples the ClearScript and Jurassic).

In version 6.X, state is lost after an exception is thrown

Hello, Jeremy!

After upgrading from version 5.4.4 to 6.1.0, some my tests began to fail. Upon a detailed research, it turned out that after any errors occur in JavaScript code, state is lost.

To reproduce this error, I wrote a console application:

using System;
using System.Threading.Tasks;

using Jering.Javascript.NodeJS;

namespace TestJeringNodeJS
{
    public class Program
    {
        const string MODULE_FILE_NAME = "counter.js";
        const string MODULE_CODE = @"
let counter = 0;

module.exports.increaseCounter = (callback, num) => {
    if (num < 0) {
        throw new Error('The value cannot be negative!');
    }

    let result = counter += num;
    callback(null, result);
}";


        public static void Main(string[] args)
        {
            IncreaseCounter(3);
            IncreaseCounter(4);
            IncreaseCounter(-1);
            IncreaseCounter(5);
        }

        private static void IncreaseCounter(int num)
        {
            try
            {
                int result = InvokeEngineHelper<int>("increaseCounter", new object[] { num });

                Console.WriteLine("Result: {0}", result);
            }
            catch (InvocationException e)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(e.Message);
                Console.ForegroundColor = ConsoleColor.White;
            }
        }

        private static T InvokeEngineHelper<T>(string exportName = null, object[] args = null)
        {
            Task<(bool, T)> cachedTask = StaticNodeJSService.TryInvokeFromCacheAsync<T>(MODULE_FILE_NAME,
                exportName, args);
            (bool success, T result) = cachedTask.ConfigureAwait(false).GetAwaiter().GetResult();

            if (success)
            {
                return result;
            }
            else
            {
                Task<T> task = StaticNodeJSService.InvokeFromStringAsync<T>(MODULE_CODE, MODULE_FILE_NAME,
                    exportName, args);

                return task.ConfigureAwait(false).GetAwaiter().GetResult();
            }
        }
    }
}

When using version 5.4.4, state after the error occurs is preserved:

Result: 3
Result: 7
The value cannot be negative!
Error: The value cannot be negative!
    at module.exports.increaseCounter (anonymous:6:15)
    at Server.<anonymous> ([eval]:1:4360)
    at Generator.next (<anonymous>)
    at [eval]:1:1271
    at new Promise (<anonymous>)
    at r ([eval]:1:1016)
    at IncomingMessage.<anonymous> ([eval]:1:2634)
    at IncomingMessage.emit (events.js:327:22)
    at endReadableNT (internal/streams/readable.js:1327:12)
    at processTicksAndRejections (internal/process/task_queues.js:80:21)
Result: 12

When using version 6.1.0, state after the error occurs is lost:

Result: 3
Result: 7
The value cannot be negative!
Error: The value cannot be negative!
    at module.exports.increaseCounter (anonymous:6:15)
    at Server.<anonymous> ([eval]:1:2443)
    at Generator.next (<anonymous>)
    at [eval]:1:355
    at new Promise (<anonymous>)
    at o ([eval]:1:100)
    at IncomingMessage.<anonymous> ([eval]:1:557)
    at IncomingMessage.emit (events.js:327:22)
    at endReadableNT (internal/streams/readable.js:1327:12)
    at processTicksAndRejections (internal/process/task_queues.js:80:21)
Result: 5

Ability to configure node runtime

In the NodeJSProcessFactory, you've hardcoded 'node' as the startup executable. Could this be configurable as part of the NodeJSProcessOptions?

If there are multiple versions of node installed, I'd like to specify which to use directly, rather than relying on the version specified in the system's PATH. What do you think?

Sending parameters

This is not an issue, but a question.
How can I send parameters to module.exports?
I have this:
module.exports = (callback, exportSettings) in ts file and this in c#:
image = await StaticNodeJSService.InvokeFromFileAsync("test_nodejs_script.js",
args: new [] { exportSettings });
I am not sure the ts file gets exportSettings string.
Also how can I have a breakpoint in ts file?

Thanks

Question about concurrency of multiple independent caller processes

Hi,

I have a build server which runs many builds at the same time. Part of the build is running tests. One of the tests is an integration test that calls node.js using this library.

Let's say I have 4 instances of this test running from 4 different calling processes (MSBUILD), is the node.js listener server script written in a way, that it support multiple instances of it co-existing?

Co-debug and JavaScript exception handling

Hi there,

I am using JetBrains Rider to co-debug (simultaneously debug) C# and JavaScript (actually TypeScript via source maps).

Rider has a nice "Attach to Node.js/Chrome" debug config which crucially includes an option to "Reconnect automatically". Thus I can just leave this debug config on and it always picks up calls to JavaScript from StaticNodeJSService.InvokeFromFileAsync() when options.NodeAndV8Options = "--inspect-brk". I can thus concentrate on starting and stopping C# code and watch both C# and TypeScript break points get hit which is fantastic.

So far so good.

However when I set Rider to automatically break on (caught) JavaScript exceptions, it always breaks immediately following StaticNodeJSService.InvokeFromFileAsync() with the following exception:

ReferenceError: Cannot access 'd' before initialization
    at [eval]:1:2103
    at Object.<anonymous> ([eval]:1:2395)
    at n ([eval]:1:124)
    at [eval]:1:923
    at [eval]:1:932
    at Script.runInThisContext (vm.js:120:20)
    at Object.runInThisContext (vm.js:311:38)
    at Object.<anonymous> ([eval]-wrapper:10:26)
    at Module._compile (internal/modules/cjs/loader.js:1156:30)
    at evalScript (internal/process/execution.js:94:25)

which comes from try{e=i._makeLong(d); in some code called [eval] which seems to be some kind of JavaScript wrapper. The exception is caught and perhaps the code is perfectly functioning as designed.

Also all my user code exceptions are also caught (again great in the general case - seems exceptions are effectively re-thrown in C# with nice stack trace).

Unfortunately though this means to break on JavaScript terminating exceptions in my code I need to configure Rider to stop on caught JavaScript exceptions.... including the exception in [eval] which seems to be triggered every time JavaScript is called.

I am wondering if you might therefore consider providing an option to not catch top-level (uncaught) user exceptions in JavaScript so that I can configure Rider to break on uncaught exceptions to see terminating failures in JavaScript debugging context? Obviously even I would not want this most of the time but when co-debugging it would be useful.

Also if the exception in [eval] is a bug it would make exception breaking easier if it were fixed (or designed away).

Any alternative thoughts you have would be very welcome and thanks for this tool!

BR,
Mark

Received a HTTP response with an unexpected status code: ServiceUnavailable

There is a problem when trying to take into use:

{
  "exceptionType": "InvocationException",
  "message": "Received a HTTP response with an unexpected status code: ServiceUnavailable.",
  "stackTrace": "   at Jering.Javascript.NodeJS.HttpNodeJSService.TryInvokeAsync[T](InvocationRequest invocationRequest, CancellationToken cancellationToken)",
  "failingDependencyUri": null
}

when using example code

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.
}";

Question: Example to replace aspnet-prerendering in asp.net core 3.1?

Hey,
I hope this is the right place.
At the moment, I try to reach ssr with angular under asp.net core 3.1 and want to use your library. Is there a good exaple? Have I replace many code or have I only write some lines?
I don't know how to do that, so maybe someone can point me in the right direction?

all the best,
Christopher

Error Json Value cannot be converted to byte[]

I tried using your library to execute QrCode by Nodejs. I get the error Json Value cannot be converted to byte[].
I beleieve part of the problem is the use of System.Text.Json instead of Newtonsoft.Json.
How can I change the deserialization process.

if System.Text.Json is not the issue how can we use your library to consume qr-image node module?

Pooling support for high request rates?

Would there be problems having multiple instances? Example use: A high traffic site that needs to do lots of vue/react SSR. A single nodejs process could become CPU-limited.

The readme says to avoid it, but are there any other consequences?

Try to avoid creating multiple INodeJSService instances since by default, each instance spawns a NodeJS process.

Also, if you are using the static API from multiple threads and the NodeJS process is performing invocations for other threads, you might get unexpected results.

For the static API, does that mean we need to implement our own concurrency control on top of it?

There's an older issue in the aspnet repo where someone put up some sample pooling code, for reference:
aspnet/JavaScriptServices#1442 (comment)

I think it would be so valuable to the .net community to have an out-of-the-box pooled nodejs service.

How to debug JavaScript when using Jering.Javascript.NodeJS (Fetch-Post)

Hello:
I recently need to run some Node.JS code to fetch(POST) some web server response in string text.
The following is my situation:
My OS: Windows 10 (latest version)
Node.js: 16.4.0 (x64)
I have installed the following npm packages:

C:\Temp>npm list
[email protected] C:\Temp
`-- [email protected]

The following is the content for fetch.js:
C:\Temp>type fetch2.js

const fetch = require('node-fetch');
async function fetch_data1()
{
  const url = 'https://sport.betregal.com/pagemethods_ros.aspx/UpdateEvents'
  const body1 = 'requestString=55677001';
  const cookies_now = 'XXXX'
  const res =
await fetch(url, {method:'POST', body: body1, 
headers: { "Accept": "*.*", "sec-fetch-mode": "no-cors", "Access-Control-Allow-Origin": "*", "requesttarget": "AJAXService", "cookie": cookies_now,  "Content-Type": "application/x-www-form-urlencoded" }});
  const data = await res.text();
  console.log(data)
}

fetch_data1();

C:\Temp>
I can run my Node.js script (index.js) without any issue:
C:\Temp> node fetch.js

I created one C# Console App.
I added the nuget page:
Install-Package Jering.Javascript.NodeJS -Version 6.0.1
I added this JS file to the project: (fetch.js)

const fetch = require('node-fetch');

module.exports = (callback, payload) => {
    (async () => {
        const url = 'https://sport.betregal.com/pagemethods_ros.aspx/UpdateEvents'
        const cookies_now = 'XXXX'
        try {
            const res =
                await fetch(url, {
                    method: 'POST', body: payload, headers: {
                        "Accept": "*.*", "sec-fetch-mode": "no-cors", "Access-Control-Allow-Origin": "*",
                        "requesttarget": "AJAXService", "cookie": cookies_now,
                        "Content-Type": "application/x-www-form-urlencoded"
                    }
                });
            const data = await res.text();
            debugger;
            callback(null, data);
        } catch (err) {
            console.error(err);
            callback(err);
        } finally {
            console.log('Done');
        }
    });
}

And in my C# main program, I have the following code: (Target .NET 5.0)

using Jering.Javascript.NodeJS;
using System;
using System.Threading.Tasks;

namespace BetRegalEventsMarketsNode
{
    class Program
    {
        public const string Path_To_JS_File = @"C:\Temp\fetch.js";
        static async Task Main()
        {
            string text_data =
                await StaticNodeJSService.InvokeFromFileAsync<string>(Path_To_JS_File, args: new[] { "requestString=55677001" });
        }
    }
}

I can run compile my program without issue.
But when I run my program, I can't see any return data. I tried to debug my program, as I put 'debugger' in fetch.js file, but it seems program not running at all.
Let me know how I can debug my program or if I made any syntax errors in my JavaScript code.
I just use one simple Node Fetch function to post some data and get return some JSON format data back from the web server.
By the way, as the cookies will be expired in about 2 hours, can I pass cookies as a parameter from C# main program every 2 hours?

An established connection was aborted by the software in your host machine

Sometime we got that error


An invocation attempt failed. Retries remaining: 1. Exception: System.Net.Http.HttpRequestException: Error while copying content to a stream. ---> System.IO.IOException: Unable to read data from the transport connection: An established connection was aborted by the software in your host machine.. ---> System.Net.Sockets.SocketException (10053): An established connection was aborted by the software in your host machine. 
--- End of inner exception stack trace --- at System.Net.Http.HttpConnection.WriteAsync(ReadOnlyMemory`1 source) 
at System.Net.Http.HttpConnection.ChunkedEncodingWriteStream.<WriteAsync>g__WriteChunkAsync\|2_0(HttpConnection connection, ReadOnlyMemory`1 buffer) 
at System.Text.Json.JsonSerializer.WriteAsyncCore(Stream utf8Json, Object value, Type inputType, JsonSerializerOptions options, CancellationToken cancellationToken) 
at Jering.Javascript.NodeJS.InvocationContent.SerializeToStreamAsync(Stream stream, TransportContext context) at System.Net.Http.HttpContent.CopyToAsyncCore(ValueTask copyTask) --- End of inner exception stack trace --- at System.Net.Http.HttpContent.CopyToAsyncCore(ValueTask copyTask) at System.Net.Http.HttpConnection.SendRequestContentAsync(HttpRequestMessage request, HttpContentWriteStream stream, CancellationToken cancellationToken) 
at System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken) 
at System.Net.Http.HttpConnectionPool.SendWithNtConnectionAuthAsync(HttpConnection connection, HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken) at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken) 
at System.Net.Http.RedirectHandler.SendAsyn…

I suppose that happen because Content-Length is not setted here and HttpClient and node-js works in chunked mode
https://github.com/dotnet/corefx/blob/master/src/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/ChunkedEncodingReadStream.cs
and
https://github.com/dotnet/corefx/blob/master/src/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/ContentLengthReadStream.cs

by documentation here

Sending a 'Content-Length' header will disable the default chunked encoding.

For set
res.setHeader('Content-Length', Buffer.byteLength(responseJson));
and for string case too

Also thats can be increase performance for nodejs and HttpClient, need benchmarks :)

Exit if parent process dies

When developing locally, it's frustrating to have node.exe still running if the dotnet process terminates. It would be awesome to detect this from within the Node instance and clean up.

The .NET Core NodeServices middleware uses a clever approach to determine whether to kill the child Node process by polling the parent process PID.
https://github.com/dotnet/aspnetcore/blob/8d2d2f6c012751970cc1d5ec04e0c606c6f7ca06/src/Middleware/NodeServices/src/Content/Node/entrypoint-http.js#L367-L395

Going to pull the latest version of the package to confirm the behavior still exists, but this was an issue when I was experimenting a few days ago.

Can I use chrome-remote-interface with Jering.Javascript.NodeJS?

Hello:
I happen to find this great repo., and I want to know if I can use it to run some Node.js script, in which npm package ‘chrome-remote-interface’ is used.
The following is my situation:
My OS: Windows 10 (latest version)
Node.js: version 15.9.0 (rather new version, even the current version is: 15.10.0)
I installed Google Chrome in my Windows PC (Version 88.0.4324.190)
I run chrome with this command: chrome --remote-debugging-port=9222
I have installed the following npm packages:
C:\Temp>type package.json
{
"name": "Test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo "Error: no test specified" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"chrome-remote-interface": "^0.29.0",
"express": "^4.17.1",
"node-fetch": "^2.6.1",
}
}

The following is the content for index.js:
C:\Temp>type index.js
const CDP = require('chrome-remote-interface');

CDP(async(client) => {
const {Network, Page, Runtime} = client;
try {
await Network.enable();
await Page.enable();
await Network.setCacheDisabled({cacheDisabled: true});
await Page.navigate({url: 'https://www.google.com/'});
await Page.loadEventFired();
const result = await Runtime.evaluate({
expression: 'document.documentElement.outerHTML'
});
const html = result.result.value;
console.log(html);
} catch (err) {
console.error(err);
} finally {
client.close();
}
}).on('error', (err) => {
console.error(err);
});

I can run my Node.js script (index.js) without any issue:
C:\Temp> node index.js

My question is: how I can do the same with Jering.Javascript.NodeJS?
I have downloaded the repo in zip format, and unzip it and tried to understand it.
I am using Visual Studio 2019 (Version 16.8.6), when I tried to rebuild the repo., I got 8 errors:
Error NU1403 Package content hash validation failed for Microsoft.DotNet.PlatformAbstractions.2.1.0. The package is different than the last restore.
Package content hash validation failed for Microsoft.NETCore.Platforms.2.0.0. The package is different than the last restore.
Package content hash validation failed for Microsoft.NETCore.Targets.1.1.0. The package is different than the last restore.
Package content hash validation failed for runtime.debian.8-x64.runtime.native.System.Security.Cryptography.OpenSsl.4.3.0. The package is different than the last restore.
Package content hash validation failed for runtime.native.System.4.3.0. The package is different than the last restore.
…..
I wish I can port this repo to target .Net 5.0, which will be the future for all .Net platform.
But I don’t know how to fix those above errors first.
Besides, I looked at the repo., I have no idea how I can set up one small test case, so I can test my Node.js script: index.js
Please advise!

Does it support highlight.js

Hi~

I am using C# to develop a Microsoft Word plugin. I want to highlight some source code to be written in MS Word.

Once I tried to make a parser, but there were so many different languages to be supported. That is too hard. So I turned to a famous JavaScript lib which was called highlight.js.

However, another problem occurred. I have to run js in the .Net environment. Firstly, I tried the Microsoft JScript .Net library. After I learned how to use it, I found that it doesn't support ECMA6 or the newer version. So I try to use Jering's lib.

I wonder whether this project will satisfy my need. I want Node.JS to run the highlight.js and give me the rendered HTML to paste into the Word document. Thanks!

My Project: https://github.com/LittleNewton/Equation_and_Codebox
Highlight.js: https://highlightjs.org/

net461 package depends on .NET Core

First of all, thanks for shipping this project!

I'm working on pulling it in to React.NET here: reactjs/React.NET#1021

I observed that the nuget package targeting net461 pulls in a few .NET Core dependencies, such as:

Microsoft.AspNetCore.Hosting.Abstractions (>= 2.1.0)

As well as a few .NET Standard dependencies which appear to be .NET Core related, but upon further inspection might just work in a Net Framework application:

Microsoft.Extensions.DependencyInjection (>= 2.1.0)
Microsoft.Extensions.Logging (>= 2.1.0)
Microsoft.Extensions.Options (>= 2.1.0)

Is there a sample somewhere for how to get this working in a .NET Framework application? In the meantime I've cloned the project locally and going to dig further...

node.js process not properly disposed after timeout is hit

am trying to add a timeout to the invocation to avoid possible endless loops from user-created scripts. i tried setting
StaticNodeJSService.Configure(options => options.TimeoutMS = 2000);
and also adding a cancellation token to the invokeFromStringAsync method.
i also wrapped the invocation into a try/catch block that calls StaticNodeJSService.DisposeServiceProvider();

despite i still have orphaned nodejs processes after running my unit tests with an endless looping script.

Error message has newline (\n) character in it?

Let's say in the module.exports that I expose to .NET I do this:

catch (error) {
    throw "TEST"
}

Back in .NET, the exception is caught just fine as expected (I'm wrapping a try / catch around nodeJSService.InvokeFromFileAsync), but if I examine exception.Message, I don't get TEST as expected, I get TEST\n.

In .NET this is trivial to remove, but it shouldn't be there in the first place, right? I figured I would report this unexpected behavior here, and also ask if I am doing something wrong to cause this newline character to be in my exception message?

Anyway, super cool package - it's helping me call some external TypeScript / JavaScript code that would be near impossible to port into the C# language!

Deep argument serialization

Hi,

Trying to pass arguments inside:
module.exports = (callback, arg1, arg2, arg3)

I have an object, let's say Person. Who has a List and Adress has fields StreetName and City.

Currently it looks like:
class Person {
string Name; // is serialized
List... // is not serialized

}

Also if I pass a List as an argument inside arg2 for example, I do not have access to AddressInList.StreetName - undefined.

Looks like arg1, arg2, arg3 does shallow serialization when sending to node script. Is this correct?

NPM dependencies

Hi,

Couldn't find any documentation (or maybe I missed it) on how to use it when using npm dependencies in the module you're executing. Found a few entries here, in the issues, but I'd like to know things like: does it use a packages.json, if present on disk and who runs npm install?

Also, nice lib btw.

Thanks

Connection Exception when running on Azure App Service

We are having trouble using Jering.Javascript.NodeJS on and Azure App Service running Windows. But only in a specific scenario.

The setup we have with Jering.Javascript.NodeJS is as follows:

Azure App Service running a Windows, .NET framework 4.8, ASP.NET and using node 14.16.0(preinstalled on the App Service by default).

ASP.NET controller using Jering.Javascript.NodeJS to render JavaScript components to HTML.

Once the controller kicks in and StaticNodeJSService.InvokeFromFileAsync<string>(...); is called, then a child proces is started for node.exe under w3p.exe and Jering.Javascript.NodeJS does it magic.

It all works like a charm, and we LOVE it.

BUT when we turn on Application Insights in our Azure subscription, we run into trouble. Connections to the node.exe process times out. We can still see a child proces is started for node.exe under w3p.exe, but now Jering.Javascript.NodeJS throws a connection exception. The point in code that thows the exception is here:

throw new ConnectionException(string.Format(Strings.ConnectionException_OutOfProcessNodeJSService_ConnectionAttemptTimedOut,

That won't do. So we turn off application insights, and the all is good again.

Have anyone out there experienced something somewhat similar. We would love any input .

Documentation question

If I understand it correctly, the NodeJsProcessOptions configures the singleton service that communicates with the out of process node service via http. Is that correct? The name "NodeJsProcessOptions" implies that this is an alternative way to spawning an out of process node instance by running an in-process one. Which I'm assuming is not correct? This library doesn't have a way of running node in process?

Linux support

It would be awesome to have first-class support for automating Node instances on Linux. Just like Windows, Node would already need to be installed on the environment.

Use case:

  • Deploy as a part of a .NET core app in a Docker container
  • Much less overhead and cost to manage a Linux instance on Digital Ocean / AWS
  • Allows supporting ARM targets, for instance, Raspberry PI.

Challenges:

  • Entirely different process model, spawning & cleaning up Node instances will have platform-specific quirks
  • Different path structure consider when resolving modules

https://github.com/reactjs/React.NET/ currently supports Windows, OS X, and Linux as distribution targets via JSEngineSwitcher.ChakraCore by shipping binary blobs of the ChakraCore runtime, resolved at runtime. This only works on x64 platforms, however.

App crash on large number of errors

When a heavy load and a large number of errors from node.js, the application crashes with an error

Index was outside the bounds of the array.
   at System.String.get_Chars(Int32 index)
   at Jering.Javascript.NodeJS.OutOfProcessNodeJSService.TryCreateMessage(StringBuilder stringBuilder, String data, String& message)
   at Jering.Javascript.NodeJS.OutOfProcessNodeJSService.ErrorDataReceivedHandler(Object sender, DataReceivedEventArgs evt)
   at System.Diagnostics.Process.ErrorReadNotifyUser(String data)
   at System.Diagnostics.AsyncStreamReader.FlushMessageQueue(Boolean rethrowInNewThread)
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Diagnostics.AsyncStreamReader.<>c.<FlushMessageQueue>b__18_0(Object edi)
   at System.Threading.QueueUserWorkItemCallback.<>c.<.cctor>b__6_0(QueueUserWorkItemCallback quwi)
   at System.Threading.ExecutionContext.RunForThreadPoolUnsafe[TState](ExecutionContext executionContext, Action`1 callback, TState& state)
   at System.Threading.QueueUserWorkItemCallback.Execute()
   at System.Threading.ThreadPoolWorkQueue.Dispatch()

Add a method to manually invalidate the cached script

In addition to the file-watcher, why not adding a method to manually force the script reload from file?

The FileSystemWatcher is rather expensive, and sometimes (like my case) the file change seldomly happens. So, I we expose the MoveToNewProcess method to the interface, that would be publicly callable, and the game should be over.

Is that feasible?

Modifiable objects passed to scripts?

I'm assuming that since execution is out-of-process, there's no way to pass back modified values for arguments to a script. I've experimented with both simple types and with collections and neither allowed this. No real issue, just wanted to clarify that this was the case.

Also, I've been passing a Dictionary<string,object> instance to scripts to represent the equivalent of a JSON object, and it just magically "works". Nice job! Is that the optimal approach to use?

Support for promises / async-await?

Would love it if

functionToInvoke.apply(null, args.concat(invocationRequest.args));

could be amended to take into account a potential Promise return value and work with it.
That way modules that hold the RPC function entrypoints can use async/await and forego the callback approach.

Callback-first;error-first is a Node.js convention, but in the face of promises and async/await becoming standardized - also one they very much regret. Would be good to have options.

Jering.Javascript.NodeJS.ConnectionException on Azure App Service

Hi! I am currently experiencing an error when deploying an app to a Linux App Service running .NET 5.

I have checked to make sure node is available for the app via kudu and it should be in the PATH printed in the exception.

---> Jering.Javascript.NodeJS.ConnectionException: Failed to connect to NodeJS. Refer to the inner exception for details.
--
  | ---> System.InvalidOperationException: Failed to start Node process. To resolve this:
  |  
  | [1] Ensure that NodeJS is installed and can be found in one of the PATH directories. The current PATH enviroment variable is: /opt/dotnetcore-tools:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/home/site/wwwroot. Make sure that the Node executable is in one of those directories, or update your PATH.
  |  
  | [2] Refer to the InnerException for further details.
  | ---> System.ComponentModel.Win32Exception (2): No such file or directory
  | at System.Diagnostics.Process.ForkAndExecProcess(String filename, String[] argv, String[] envp, String cwd, Boolean redirectStdin, Boolean redirectStdout, Boolean redirectStderr, Boolean setCredentials, UInt32 userId, UInt32 groupId, UInt32[] groups, Int32&amp; stdinFd, Int32&amp; stdoutFd, Int32&amp; stderrFd, Boolean usesTerminal, Boolean throwOnNoExec)
  | at System.Diagnostics.Process.StartCore(ProcessStartInfo startInfo)
  | at System.Diagnostics.Process.Start()
  | at System.Diagnostics.Process.Start(ProcessStartInfo startInfo)
  | at Jering.Javascript.NodeJS.NodeJSProcessFactory.CreateProcess(ProcessStartInfo startInfo)
  | --- End of inner exception stack trace ---
  | at Jering.Javascript.NodeJS.NodeJSProcessFactory.CreateProcess(ProcessStartInfo startInfo)
  | at Jering.Javascript.NodeJS.NodeJSProcessFactory.Create(String serverScript)
  | at Jering.Javascript.NodeJS.OutOfProcessNodeJSService.CreateAndSetUpProcess(EventWaitHandle waitHandle)
  | at Jering.Javascript.NodeJS.OutOfProcessNodeJSService.ConnectIfNotConnected()
  | --- End of inner exception stack trace ---
  | at Jering.Javascript.NodeJS.OutOfProcessNodeJSService.ConnectIfNotConnected()
  | at Jering.Javascript.NodeJS.OutOfProcessNodeJSService.TryInvokeCoreAsync[T](InvocationRequest invocationRequest, CancellationToken cancellationToken)
  | at Jering.Javascript.NodeJS.OutOfProcessNodeJSService.InvokeFromStringAsync[T](String moduleString, String cacheIdentifier, String exportName, Object[] args, CancellationToken cancellationToken)

Kudu

$ whereis node
node: /usr/local/bin/node
$ node -v
v10.22.0

Getting error System.Net.Http.HttpRequestException: An error occurred while sending the request for a long duration request on a Linux docker

I am running a request that takes more than 10 minutes. The same request works fine when I run it locally on my Windows machine. But when the solution is deployed in a docker, it gives this error after around 4 minutes. I suspect some timeout is triggering and aborting connection. I am using Node 12.x for my purpose. Any idea?

System.Net.Http.HttpRequestException: An error occurred while sending the request.
---> System.IO.IOException: The request was aborted.
---> System.IO.IOException: The response ended prematurely, with at least 9 additional bytes expected.
at System.Net.Http.Http2Connection.ReadAtLeastAsync(Stream stream, Memory1 buffer, Int32 minReadBytes) at System.Net.Http.Http2Connection.EnsureIncomingBytesAsync(Int32 minReadBytes) at System.Net.Http.Http2Connection.ReadFrameAsync(Boolean initialFrame) at System.Net.Http.Http2Connection.ProcessIncomingFramesAsync() --- End of inner exception stack trace --- at System.Net.Http.Http2Connection.Http2Stream.CheckResponseBodyState() at System.Net.Http.Http2Connection.Http2Stream.TryEnsureHeaders() at System.Net.Http.Http2Connection.Http2Stream.ReadResponseHeadersAsync(CancellationToken cancellationToken) at System.Net.Http.Http2Connection.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) --- End of inner exception stack trace --- at System.Net.Http.Http2Connection.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken) at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) at Microsoft.Extensions.Http.Logging.LoggingHttpMessageHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) at Microsoft.Extensions.Http.Logging.LoggingScopeHttpMessageHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) at System.Net.Http.HttpClient.FinishSendAsyncUnbuffered(Task1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)
at Jering.Javascript.NodeJS.HttpNodeJSService.TryInvokeAsync[T](InvocationRequest invocationRequest, CancellationToken cancellationToken)
at Jering.Javascript.NodeJS.OutOfProcessNodeJSService.TryInvokeCoreAsync[T](InvocationRequest invocationRequest, CancellationToken cancellationToken)
at Jering.Javascript.NodeJS.OutOfProcessNodeJSService.InvokeFromFileAsync[T](String modulePath, String exportName, Object[] args, CancellationToken cancellationToken)

Callback arguments are not always optional

It seems the callback arguments are only optional when the return type is string. For anything else they are not always optional. For example, the following all work as expected:

string resultStr = await StaticNodeJSService
    .InvokeFromStringAsync<string>("module.exports = (callback, message) => callback(null, message);", args: new[] { "success" });
resultStr = await StaticNodeJSService
    .InvokeFromStringAsync<string>("module.exports = (callback, message) => callback(undefined, message);", args: new[] { "success" });
resultStr = await StaticNodeJSService
    .InvokeFromStringAsync<string>("module.exports = (callback) => callback(undefined, 'success');");
resultStr = await StaticNodeJSService
    .InvokeFromStringAsync<string>("module.exports = (callback) => callback();");
int resultNum = await StaticNodeJSService
    .InvokeFromStringAsync<int>("module.exports = (callback) => callback(undefined, 7);");
object resultObj = await StaticNodeJSService
    .InvokeFromStringAsync<object>("module.exports = (callback) => callback(undefined, { result: 'success' });");
resultObj = await StaticNodeJSService
    .InvokeFromStringAsync<object>("module.exports = (callback) => callback(undefined, {});");

And the following throw the expected exception:

resultStr = await StaticNodeJSService
    .InvokeFromStringAsync<string>("module.exports = (callback) => callback(new Error('Expected exception.'));");
resultNum = await StaticNodeJSService
    .InvokeFromStringAsync<int>("module.exports = (callback) => callback(new Error('Expected exception.'));");
resultObj = await StaticNodeJSService
    .InvokeFromStringAsync<object>("module.exports = (callback) => callback(new Error('Expected exception.'));");

However, the following I would expect to work:

resultNum = await StaticNodeJSService
    .InvokeFromStringAsync<int>("module.exports = (callback) => callback();");
resultNum = await StaticNodeJSService
    .InvokeFromStringAsync<int>("module.exports = (callback) => callback(undefined, NaN);");
resultObj = await StaticNodeJSService
    .InvokeFromStringAsync<object>("module.exports = (callback) => callback();");

But they throw this exception (each have different inner exceptions):

Exception has occurred: CLR/System.Text.Json.JsonException
Exception thrown: 'System.Text.Json.JsonException' in System.Private.CoreLib.dll: 'The input does not contain any JSON tokens. Expected the input to start with a valid JSON token, when isFinalBlock is true. Path: $ | LineNumber: 0 | BytePositionInLine: 0.'
 Inner exceptions found, see $exception in variables window for more details.

I would preferred a fix so that they work but at the least, the documentation could be changed to reflect reality, particularly section https://github.com/JeringTech/Javascript.NodeJS#function-with-callback-parameter.

Issue running with node 13/14

It appears there are issues running on newer versions of node 13 and 14. I have gotten it to work with node 13.8.0 but it fails on 13.14.0 or latest node 14.

I get this error whenever I try to run it inside of a docker container:

node[64]: ../src/node_http_parser.cc:523:static void node::{anonymous}::Parser::Initialize(const v8::FunctionCallbackInfo<v8::Value>&): 
Assertion `args[4]->IsInt32()' failed.
 1: 0xa0e670 node::Abort() [node]
 2: 0xa0e6ee  [node]
 3: 0xa2447a  [node]
 4: 0xbf0cec  [node]
 5: 0xbf2af7 v8::internal::Builtin_HandleApiCall(int, unsigned long*, v8::internal::Isolate*) [node]
 6: 0x13da5f9  [node]

It appears to error out on this line: https://github.com/nodejs/node/blob/v13.14.0/src/node_http_parser.cc#L523

    if (args.Length() > 4) {
      CHECK(args[4]->IsInt32());
      headers_timeout = args[4].As<Number>()->Value();
    }

so it looks related to the header timeout perhaps? Maybe the number being set in HttpServer.ts is too large and not a valid int32?

Error: Cannot find module 'xmldom'

Hi

I'm having problems using the InvokeFromFileAsync method when my js file uses the dependency of other modules, below the settings and details of my implementation.

Index.js

module.exports = (callback, gpxString) => {  // Module must export a function that takes a callback as its first parameter

    const tj = require("@tmcw/togeojson");
    // node doesn't have xml parsing or a dom. use xmldom
    const DOMParser = require("xmldom").DOMParser;
    const gpx = new DOMParser().parseFromString(gpxString);
    const converted = tj.gpx(gpx);

    //    const convertedWithStyles = tj.kml(kml, { styles: true });

    var result = converted; // Your javascript logic

    callback(null /* If an error occurred, provide an error object or message */, result); // Call the callback when you're done.
}

.net project configuration:

public class NodeJSDepedencies : IDependencyGroup
    {
        public void Register(ILogger logger, IServiceCollection services)
        {
            services.AddNodeJS();

            ServiceProvider serviceProvider = services.BuildServiceProvider();
            // Options for the NodeJSProcess, here we enable debugging
            services.Configure<NodeJSProcessOptions>(options =>
            {
                options.NodeAndV8Options = "--inspect-brk";
                options.ProjectPath = @"C:\PersonalWorkspace\ConvertGPXToGeoJson\src";
            });

            // Options for the service that manages the process, here we make its timeout infinite
            services.Configure<OutOfProcessNodeJSServiceOptions>(options => options.TimeoutMS = -1);


            INodeJSService nodeJSService = serviceProvider.GetRequiredService<INodeJSService>();
            services.TryAddSingleton<INodeJSService>(serviceProvider.GetRequiredService<INodeJSService>());
        }
    }

Call InvokeFromFileAsync:

var result2 = await _nodeJSService.InvokeFromFileAsync<dynamic>("index.js", args: new[] { text });

Error:
Cannot find module 'xmldom'\nRequire stack:\n- C:\\PersonalWorkspace\\ConvertGPXToGeoJson\\src\\index.js\n- C:\\PersonalWorkspace\\ConvertGPXToGeoJson\\src\\[eval]\r\nError: Cannot find module 'xmldom'\nRequire stack:\n- C:\\PersonalWorkspace\\ConvertGPXToGeoJson\\src\\index.js\n- C:\\PersonalWorkspace\\ConvertGPXToGeoJson\\src\\[eval]\n at Function.Module._resolveFilename (internal/modules/cjs/loader.js:880:15)\n at Function.Module._load (internal/modules/cjs/loader.js:725:27)\n at Module.require (internal/modules/cjs/loader.js:952:19)\n at require (internal/modules/cjs/helpers.js:88:18)\n at module.exports (C:\\PersonalWorkspace\\ConvertGPXToGeoJson\\src\\index.js:6:23)\n at Server.<anonymous> ([eval]:1:4360)\n at Generator.next (<anonymous>)\n at [eval]:1:1271\n at new Promise (<anonymous>)\n at r ([eval]:1:1016)

Security concern: Is the node process isolated from the file system or network?

In use cases where JavaScript come comes from front end and we don't know exactly what that code is doing would be nice if the node process would be isolated without the ability to access the file system or network.

Deno does the above by default. World it be difficult to support deno along with node and be able to execute JavaScript using a deno subprocess?

Removing NodeJS Console Window

Hello there,

I'm unsure if this is an issue or a lack of understanding on my own part but I can't find anything mentioning it in the documentation.

I use InvokeFromFileAsync to execute a NodeJS script in a C# Windows Forms application. It works great, however there is a Node console window popup every time the script is executed. It doesn't really add anything to my UI and I'm unsure how to execute the process completely in the background so this popup doesn't occur.

Screen Shot 2021-01-12 at 11 37 43 AM

Any help is appreciated,

Thank you!

Security Concern: Library opens socket on localhost that can be used by an attacker to execute arbitary code

If i understand this library correctly, it opens an unsecured HTTP server on localhost, that accepts connections that can execute arbitrary code. This code will be executed with the permissions of the user that runs a Javascript.NodeJS application.

How to reproduce:

  • Find a .NET + Javascript.NodeJS process with an open HTTP server
  • Post something like that to http://localhost:port
{
	"moduleSourceType": 2,
	"moduleSource": "\r\nmodule.exports = (callback) => {const fs = require('fs'); fs.writeFileSync('pwnd.txt', 'Hello world!'); callback()}"
}

Possible attacks

  1. Local privilege escalation: A less privileged local user or attacker can gain higher privileges via this service. For example to steal database credentials or personal data

  2. Remote attack: If an attacker can utilize any other service on the same machine running Javascript.NodeJS to make arbitrary POST requests, they can execute code via Javascript.NodeJS.

Possible fixes

  1. Secure the node http endpoint somehow, via https and client certificates. Or with a bearer token, but it mustn't be passed as a command line parameter to Node, as it would be readable by any local user.
  2. Use IPC, files or unix sockets to communicate with Node, instead of TCP

Intermittent error: An attempt was made to access a socket in a way forbidden by its access permissions

We are getting the following issue intermittently:

An invocation attempt failed. Retries remaining: 5.
Exception:
System.Net.Http.HttpRequestException: An attempt was made to access a socket in a way forbidden by its access permissions.
---> System.Net.Sockets.SocketException (10013): An attempt was made to access a socket in a way forbidden by its access permissions.
at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
--- End of inner exception stack trace ---
at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.ConnectAsync(HttpRequestMessage request, Boolean allowHttp2, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.CreateHttp11ConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.GetHttpConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken)
at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.DiagnosticsHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.HttpClient.FinishSendAsyncUnbuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)
at Jering.Javascript.NodeJS.HttpNodeJSService.TryInvokeAsync[T](InvocationRequest invocationRequest, CancellationToken cancellationToken)
at Jering.Javascript.NodeJS.OutOfProcessNodeJSService.TryInvokeCoreAsync[T](InvocationRequest invocationRequest, CancellationToken cancellationToken)

We have a .Net Core 3.1 web application running on an Azure Windows App Service Server - Web sockets are Off, NodeJs version 14.15.0.
As well as hosting our website this server also uses JeringTech Javascript.NodeJS to run Javascript to create PDFs.
Currently it runs well for around 5 days and then throws the error above. We need to restart the app server to start things up again. The microsoft nodeservices package gave the same behaviour.
Our configuration is simple - the Startup.cs file contains:
services.AddNodeJS();
services.Configure(options => options.NumRetries = 5);

An existing connection was forcibly closed by the remote host.

Hi again, got another question for you. Thanks a lot for the previous help. :)

I am calling:
Stream byteStream = await _nodeService.InvokeFromFileAsync(
_nodeScript,
_nodeMethod,
args: new object[] { data});

I get this error for some reason:

System.Net.Http.HttpRequestException
  HResult=0x80131620
  Message=An error occurred while sending the request.
  Source=System.Net.Http
  StackTrace:
   at System.Net.Http.HttpConnection.<SendAsyncCore>d__53.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
   at System.Net.Http.HttpConnectionPool.<SendWithNtConnectionAuthAsync>d__48.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
   at System.Net.Http.HttpConnectionPool.<SendWithRetryAsync>d__47.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
   at System.Net.Http.RedirectHandler.<SendAsync>d__4.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
   at System.Net.Http.HttpClient.<FinishSendAsyncUnbuffered>d__71.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
   at Jering.Javascript.NodeJS.HttpNodeJSService.<TryInvokeAsync>d__7`1.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at Jering.Javascript.NodeJS.OutOfProcessNodeJSService.<TryInvokeCoreAsync>d__29`1.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
   at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
   at Jering.Javascript.NodeJS.OutOfProcessNodeJSService.<InvokeFromFileAsync>d__17`1.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task 

Inner Exception 1:
IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host..

Inner Exception 2:
SocketException: An existing connection was forcibly closed by the remote host.

Everything was working fine, no issues, but for some reason nothing works anymore. How do I debug this?

How to deploy a project with local node_modules?

If I use npm to install modules within my project structure (most likely in the root of the project), then how do you recommend I deploy the project?
Should I simply set NodeJSProcessOptions.ProjectPath to "./" and set the node_modules folder properties in visual studio to copy always?
Or would it be better to setup a folder on the server with node modules installed there. Then set that path in the NodeJSProcessOptions.ProjectPath?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.