Microsoft.JavaScript.NodeApi
0.5.7
Prefix Reserved
See the version list below for details.
dotnet add package Microsoft.JavaScript.NodeApi --version 0.5.7
NuGet\Install-Package Microsoft.JavaScript.NodeApi -Version 0.5.7
<PackageReference Include="Microsoft.JavaScript.NodeApi" Version="0.5.7" />
paket add Microsoft.JavaScript.NodeApi --version 0.5.7
#r "nuget: Microsoft.JavaScript.NodeApi, 0.5.7"
// Install Microsoft.JavaScript.NodeApi as a Cake Addin #addin nuget:?package=Microsoft.JavaScript.NodeApi&version=0.5.7 // Install Microsoft.JavaScript.NodeApi as a Cake Tool #tool nuget:?package=Microsoft.JavaScript.NodeApi&version=0.5.7
Node API for .NET: JavaScript + .NET Interop
This project enables advanced interoperability between .NET and JavaScript in the same process.
- Load .NET assemblies and call .NET APIs in-proc from a JavaScript application.
- Load JavaScript packages call JS APIs in-proc from a .NET application.
Interop is high-performance and supports TypeScript type-definitions generation, async (tasks/promises), streams, and more. It uses Node API so it is compatible with any Node.js version (without recompiling) or other JavaScript runtime that supports Node API.
⚠️ Status: Public Preview - Most functionality works well, though there are some known limitations around the edges, and there may still be minor breaking API changes.
Instructions for getting started are below.
Minimal example - JS calling .NET
// JavaScript
const Console = require('node-api-dotnet').System.Console;
Console.WriteLine('Hello from .NET!');
Minimal example - .NET calling JS
// C#
interface IConsole { void Log(string message); }
var nodejs = new NodejsPlatform(libnodePath).CreateEnvironment();
nodejs.Run(() => {
var console = nodejs.Import<IConsole>("global", "console");
console.Log("Hello from JS!");
});
For more examples, see the examples directory.
Feature Highlights
- Load and call .NET assemblies from JS
- Load and call JavaScript packages from .NET
- Generate TS type definitions for .NET APIs
- Full async support
- Error propagation
- Develop Node.js addons with C#
- Optionally work directly with JS types in C#
- Automatic efficient marshaling
- Stream across .NET and JS
- Optional .NET native AOT compilation
- High performance
- Work with .NET generic APIs in JS
Load and call .NET assemblies from JS
The node-api-dotnet
package manages hosting the .NET runtime in the JS process
(if not using AOT - see below). The .NET core library types are available immediately;
additional .NET assemblies can be loaded by file path:
// JavaScript
const dotnet = require('node-api-dotnet');
dotnet.load('path/to/ExampleAssembly.dll');
const exampleObj = new dotnet.ExampleNamespace.ExampleClass(...args);
All .NET namespaces are projected onto the top-level dotnet
object. When loading multiple .NET
assemblies, types from all assemblies are merged into the same namespace hierarchy.
Load and call JavaScript packages from .NET
Calling JavaScript from .NET requires hosting a JS runtime such as Node.js in the .NET app. Then JS packages can be imported either directly as JS values or by declaring C# interfaces for the JS types and using automatic marshalling.
All interaction with a JavaScript environment must be from its thread, via the
Run()
, RunAsync()
, or Post()
methods on the JS environment object.
// C#
interface IExample
{
void ExampleMethod();
}
var nodejsPlatform = new NodejsPlatform(libnodePath);
var nodejs = nodejsPlatform.CreateEnvironment();
nodejs.Run(() => {
// Import a module property, then call a function on it.
var example1 = nodejs.Import("example-npm-package", "ExampleObject");
example1.CallMethod("exampleMethod");
// Import the module property using an interface, and call the same function.
var example2 = nodejs.Import<IExample>("example-npm-package", "ExampleObject");
example2.ExampleMethod();
});
In the future, it may be possible to automatically generate .NET API definitions from TypeScript type definitions.
Generate TS type definitions for .NET APIs
If writing TypeScript, or type-checked JavaScript, there is a tool to generate type .d.ts
type
definitions for .NET APIs. It also generates a small .js
file that makes it simple to load the
assembly DLL and type-definitions together.
$ npm exec node-api-dotnet-generator --assembly ExampleAssembly.dll --typedefs ExampleAssembly.d.ts
// TypeScript
import './ExampleAssembly.js'; // TS also loads the adjacent .d.ts file.
dotnet.ExampleNamespace.ExampleClass.ExampleMethod(...args); // This call is type-checked!
(CommonJS modules must use require()
instead of import
.)
For reference, there is a list of C# type projections to TypeScript.
Full async support
JavaScript code can await
a call to a .NET method that returns a Task
. The marshaller
automatically sets up a SynchronizationContext
so that the .NET result is returned back to the
JS thread.
// TypeScript
import { ExampleClass } from './ExampleAssembly';
const asyncResult = await ExampleClass.GetSomethingAsync(...args);
.NET Task
s are seamlessly marshaled to & from JS Promise
s. So JS code can work naturally with
a Promise
returned from a .NET async method, and a JS Promise
passed to .NET becomes a
JSPromise
that can be await
ed in the C# code.
Error propagation
Exceptions/errors thrown in .NET or JS are propagated across the boundary with stack traces.
An unhandled .NET exception is thrown back to a JS caller as an Error
with a stack trace that
includes both .NET and JS frames, and source line numbers if symbols are available. For example:
Error: Test error thrown by JS.
at Microsoft.JavaScript.NodeApi.TestCases.Errors.ThrowDotnetError(String message) in D:\node-api-dotnet\test\TestCases\Errors.cs:line 13
at Microsoft.JavaScript.NodeApi.Generated.Module.Errors_ThrowDotnetError(JSCallbackArgs __args) in napi-dotnet.NodeApi.g.cs:line 357
at Microsoft.JavaScript.NodeApi.JSNativeApi.InvokeCallback[TDescriptor](napi_env env, napi_callback_info callbackInfo, JSValueScopeType scopeType, Func`2 getCallbackDescriptor) in JSNativeApi.cs:line 1070
at catchDotnetError (D:\node-api-dotnet\test\TestCases\errors.js:14:12)
at Object.<anonymous> (D:\node-api-dotnet\test\TestCases\errors.js:41:1)
Similarly, an unhandled JS Error
is thrown back to a .NET caller as a JSException
with a
combined stack trace.
Develop Node.js addons with C#
A C# class library project can use the [JSExport]
attribute to tag (and rename) APIs that are
exported when the library is built as a JavaScript module. A C# Source Generator runs as
part of the compilation and generates code to export the tagged APIs and marshal values between
JavaScript and C#.
// C#
[JSExport] // Export class and all public members to JS.
public class ExampleClass { ... }
public static class ExampleStaticClass
{
[JSExport("exampleFunction")] // Export as a module-level function.
public static string StaticMethod(ExampleClass obj) { ... }
// (Other public members in this class are not exported by default.)
}
The [JSExport]
source generator enables faster startup time because the marshaling code is
generated at build time rather than dynamically emitted at runtime (as when calling a pre-built
assembly). The source generator also enables building ahead-of-time compiled libraries in C# that
can be called by JavaScript without depending on the .NET Runtime. (More on that below.)
Optionally work directly with JS types in C#
The class library includes an object model for the JavaScript type system. JSValue
represents a
value of any type, and there are more types like JSObject
, JSArray
, JSMap
, JSPromise
, etc.
C# code can work directly with those types if desired:
// C#
[JSExport]
public static JSPromise JSAsyncExample(JSValue input)
{
// Example of integration between C# async/await and JS promises.
string greeter = (string)input;
return new JSPromise(async (resolve) =>
{
await Task.Delay(50);
resolve((JSValue)$"Hey {greeter}!");
});
}
Automatic efficient marshaling
There are two ways to get automatic marshaling between C# and JavaScript types:
Compile a C# class library with
[JSExport]
attributes like the examples above. The source generator produces marshaling code that is compiled with the assembly.Load a pre-built .NET assembly, as in the earlier examples. The loader will use reflection to scan the APIs, then emit marshaling code on-demand for each type that is referenced by JS. The dynamic marshalling code is derived from the same expression trees that are used for compile-time source-generation, but is generated and at runtime and compiled with
LambdaExpression.Compile()
. So there is a small startup cost from that reflection and compilation, but subsequent calls to the same APIs may be just as fast as the pre-compiled marshaling code (and are just as likely to be JITted).
The marshaller uses the strong typing information from the C# API declarations as hints about how to convert values beteen JavaScript and C#. Here's a general summary of conversions:
- Primitives (numbers, strings, etc.) are passed by value directy.
- C# structs have all properties passed by value (shallow copied).
- C# classes are passed by reference. Any JS call to a C# class or interface property or method gets proxied over to the C# instance of the class. (Object GC lifetimes are synchronized accordingly.)
- JS code may implement a C# interface, and pass that implementation back to C# code where it becomes a proxy that C# code can use.
- C# collections like
IList<T>
and JS collections likeMap<T>
are also passed by reference; access to collection elements is proxied to whichever side the real instance of the collection is on. - JS
TypedArray
s are mapped to C#Memory<T>
and passed by reference using shared memory (no proxying is needed). - Other types like enums, dates, and delegates are automatically marshaled as one would expect.
- Custom marshaling and marshaling hints may be supported later.
Stream across .NET and JS
.NET Stream
s are automatically marshalled to and from Node.js Duplex
(or Readable
or
Writable
) streams. That means JS code can seamlessly read from or write to streams created
by .NET. Or .NET code can read from or write to streams created by JS. Streamed data is
transferred using shared memory (without any additional sockets or pipes), so memory allocation
and copying is minimized.
Optional .NET native AOT compilation
This library supports hosting the .NET Runtime in the same process as the JavaScript runtime. Alternatively, it also supports building native ahead-of-time (AOT) compiled C# libraries that are loadable as a JavaScript module without depending on the .NET Runtime.
There are advantages and disadvantages to either approach: | | .NET Runtime | .NET Native AOT | |---------------------|--------------|-----------------| | API compatibility | Broad compatibility with .NET APIs | Limited compatibility with APIs designed to support AOT | | Ease of deployment | Requires a matching version of .NET to be installed on the target system | A .NET installation is not required (though some platform libs may be required on Linux/Mac) | Size of deployment | Compact - only IL assemblies need to be deployed | Larger due to bundling necessary runtime code - minimum ~3 MB per platform | | Performance | Slightly slower startup (JIT) | Slightly faster startup (no JIT) | | Runtime limitations | Full .NET functionality | Some .NET features like reflection and code-generation aren't supported |
High performance
The project is designed to be as performant as possible when bridging between .NET and JavaScript. Techniques benefitting performance include:
- Automatic marshaling avoids any use of JSON serialization, and uses generated code to avoid reflection.
- Automatic marshalling uses shared memory or proxies when possible to minimize the amount of data transferred across the boundary.
- Simple calls between JS and C# require almost zero memory allocation. (Maybe it will be zero eventually.)
- Most JavaScript values are represented in C# as small structs (basically containing just a handle to the JS value), which helps avoid memory allocation.
- Marshaling code uses modern C# performance features like
Span<T>
andstackalloc
to minimize heap allocations and copying.
Thanks to these design choices, JS to .NET calls are more than twice as fast when compared to edge-js
using
that project's benchmark.
Generics
Even though the JavaScript runtime type system lacks generics, it is possible to work with .NET generic types and methods from JavaScript:
// JavaScript
System.Enum.Parse$(System.DayOfWeek)('Tuesday');
For details, see Using .NET Generics in JavaScript.
Getting Started
Requirements
- .NET 6 or later
- .NET 8 or later is required for AOT support.
- .NET Framework 4.7.2 or later is supported at runtime, but .NET 6 SDK is still required for building.
- Node.js v16 or later
- Other JS runtimes may be supported in the future.
- OS: Windows, Mac, or Linux
- It should work on any platform where .NET 6 is supported.
Instructions
For calling .NET from JS, choose between one of the following scenarios:
- Dynamically invoke .NET APIs from JavaScript<br/>
Dynamic invocation is simpler to set up: all you need is the
node-api-dotnet
npm package and the path to a .NET assembly you want to call. But it has some limitations (not all kinds of APIs are supported), and is not quite as fast as a C# module, because marshalling code must be generated at runtime. - Develop a Node module in C#<br/> A C# Node module is appropriate for an application that has more advanced interop needs. It can be faster because marshalling code can be generated at compile time, and the shape of the APIs exposed to JavaScript can be adapted with JS interop in mind.
For calling JS from .NET, more documentation will be added soon. For now, see the
winui-fluid
example code.
Generated TypeScript type definitions can be utilized with any of these aproaches.
Development
For information about building, testing, and contributing changes to this project, see README-DEV.md.
Contributing
This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.opensource.microsoft.com.
When you submit a pull request, a CLA bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.
This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.
Trademarks
This project may contain trademarks or logos for projects, products, or services. Authorized use of Microsoft trademarks or logos is subject to and must follow Microsoft's Trademark & Brand Guidelines. Use of Microsoft trademarks or logos in modified versions of this project must not cause confusion or imply Microsoft sponsorship. Any use of third-party trademarks or logos are subject to those third-party's policies.
<br/> <br/>
Product | Versions Compatible and additional computed target framework versions. |
---|---|
.NET | net6.0 is compatible. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 was computed. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. |
.NET Framework | net472 is compatible. net48 was computed. net481 was computed. |
-
.NETFramework 4.7.2
- Microsoft.Bcl.AsyncInterfaces (>= 7.0.0)
- System.Memory (>= 4.5.5)
-
net6.0
- No dependencies.
-
net8.0
- No dependencies.
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories (1)
Showing the top 1 popular GitHub repositories that depend on Microsoft.JavaScript.NodeApi:
Repository | Stars |
---|---|
microsoft/node-api-dotnet
Advanced interoperability between .NET and JavaScript in the same process.
|
Version | Downloads | Last updated |
---|---|---|
0.8.16 | 238 | 10/15/2024 |
0.8.15 | 194 | 10/4/2024 |
0.8.14 | 102 | 10/3/2024 |
0.8.13 | 176 | 9/23/2024 |
0.8.9 | 248 | 9/6/2024 |
0.8.8 | 158 | 9/4/2024 |
0.8.7 | 175 | 9/3/2024 |
0.8.6 | 97 | 9/3/2024 |
0.8.5 | 116 | 9/1/2024 |
0.8.4 | 101 | 9/1/2024 |
0.8.3 | 193 | 8/19/2024 |
0.8.2 | 134 | 8/16/2024 |
0.8.1 | 109 | 8/15/2024 |
0.7.42 | 121 | 8/14/2024 |
0.7.41 | 124 | 8/13/2024 |
0.7.40 | 123 | 8/12/2024 |
0.7.39 | 107 | 8/12/2024 |
0.7.38 | 132 | 8/8/2024 |
0.7.37 | 92 | 8/6/2024 |
0.7.36 | 82 | 8/1/2024 |
0.7.35 | 72 | 8/1/2024 |
0.7.34 | 10,343 | 7/27/2024 |
0.7.33 | 91 | 7/24/2024 |
0.7.32 | 84 | 7/24/2024 |
0.7.31 | 299 | 7/22/2024 |
0.7.30 | 200 | 7/17/2024 |
0.7.29 | 81 | 7/16/2024 |
0.7.28 | 54 | 7/15/2024 |
0.7.26 | 83 | 7/12/2024 |
0.7.19 | 244 | 6/21/2024 |
0.7.18 | 325 | 6/17/2024 |
0.7.17 | 120 | 6/14/2024 |
0.7.16 | 132 | 6/14/2024 |
0.7.14 | 201 | 5/16/2024 |
0.7.13 | 141 | 5/15/2024 |
0.7.12 | 198 | 5/14/2024 |
0.7.11 | 142 | 5/9/2024 |
0.7.10 | 176 | 5/6/2024 |
0.7.9 | 129 | 5/2/2024 |
0.7.8 | 188 | 4/19/2024 |
0.7.7 | 130 | 4/17/2024 |
0.7.6 | 126 | 4/16/2024 |
0.7.5 | 145 | 4/14/2024 |
0.7.4 | 119 | 4/12/2024 |
0.7.3 | 124 | 4/11/2024 |
0.7.2 | 116 | 4/10/2024 |
0.7.1 | 146 | 4/8/2024 |
0.6.8 | 144 | 4/8/2024 |
0.6.7 | 126 | 4/8/2024 |
0.6.6 | 127 | 4/8/2024 |
0.6.5 | 149 | 4/5/2024 |
0.6.4 | 134 | 4/5/2024 |
0.6.3 | 156 | 3/29/2024 |
0.6.2 | 147 | 3/27/2024 |
0.6.1 | 162 | 3/26/2024 |
0.5.19 | 373 | 3/23/2024 |
0.5.18 | 144 | 3/21/2024 |
0.5.17 | 127 | 3/21/2024 |
0.5.16 | 188 | 3/20/2024 |
0.5.15 | 133 | 3/20/2024 |
0.5.14 | 146 | 3/20/2024 |
0.5.13 | 148 | 3/14/2024 |
0.5.12 | 144 | 3/12/2024 |
0.5.11 | 127 | 3/12/2024 |
0.5.10 | 128 | 3/12/2024 |
0.5.8 | 141 | 3/12/2024 |
0.5.7 | 149 | 3/11/2024 |
0.5.6 | 139 | 3/11/2024 |
0.5.4 | 142 | 3/8/2024 |
0.5.2 | 141 | 3/1/2024 |
0.5.1 | 137 | 2/27/2024 |
0.4.34 | 310 | 2/18/2024 |
0.4.33 | 386 | 2/6/2024 |
0.4.27 | 508 | 12/14/2023 |
0.4.26 | 351 | 11/21/2023 |
0.4.25 | 130 | 11/21/2023 |
0.4.24 | 128 | 11/21/2023 |
0.4.23 | 125 | 11/21/2023 |
0.4.22 | 473 | 11/11/2023 |
0.4.21 | 131 | 11/10/2023 |
0.4.20 | 125 | 11/10/2023 |
0.4.19 | 118 | 11/9/2023 |
0.4.18 | 139 | 11/6/2023 |
0.4.17 | 125 | 11/5/2023 |
0.4.16 | 174 | 10/26/2023 |
0.4.4 | 444 | 6/12/2023 |
0.3.2 | 163 | 5/28/2023 |
0.3.1 | 152 | 5/17/2023 |
0.2.33 | 242 | 5/17/2023 |
0.2.32 | 167 | 5/16/2023 |
0.2.31 | 151 | 5/9/2023 |
0.2.30 | 141 | 5/9/2023 |
0.2.29 | 147 | 5/9/2023 |
0.2.28 | 145 | 5/9/2023 |
0.2.27 | 138 | 5/7/2023 |
0.2.26 | 189 | 5/3/2023 |
0.2.25 | 180 | 5/1/2023 |
0.2.24 | 149 | 5/1/2023 |
0.2.23 | 166 | 4/30/2023 |
0.2.22 | 155 | 4/29/2023 |
0.2.21 | 168 | 4/28/2023 |
0.2.20 | 187 | 4/26/2023 |
0.2.19 | 155 | 4/26/2023 |
0.2.18 | 195 | 4/25/2023 |
0.2.17 | 157 | 4/25/2023 |
0.2.16 | 175 | 4/24/2023 |
0.2.15 | 198 | 4/23/2023 |
0.2.14 | 163 | 4/23/2023 |
0.2.13 | 178 | 4/19/2023 |
0.2.12 | 174 | 4/18/2023 |
0.2.11 | 249 | 4/17/2023 |