-
Notifications
You must be signed in to change notification settings - Fork 1
Introduction
Node dlang is a library over N-API which allows creating NodeJS native modules using only D. These modules can be directly executed by NodeJS or required from Javascript code like any other module.
For that purpose, this library automatically converts between D's and Javascript's types.
There are a couple of simple steps needed:
Create a DUB project with:
dub initAssuming JSON format, add the following fields to dub.json:
"dependencies": {
"node_dlang": "*"
},
"configurations": [
{
"name": "example_windows",
"platforms": ["windows"],
"targetType": "dynamicLibrary",
"targetPath" : ".",
"targetName" : "module.node",
"postGenerateCommands": ["move module.node.dll module.node"]
}, {
"name": "example_posix",
"platforms": ["posix"],
"targetName" : "module.node",
"targetType": "dynamicLibrary",
"postGenerateCommands": ["mv libmodule.node.so module.node"]
}
]The configurations make sure the project is built as a dynamic library (Native modules are just dynamic libraries with some special info) and rename the library with the expected .node extension.
Compilation is done with
dub buildAnd the generated module.node can be require'd from Javascript or, if the MainFunction template is used executed directly from NodeJS.
The library is imported with:
import node_dlang;As of now static functions and constant fields can be exported mixin in exportToJs:
// MainFunction is used to execute on load instead of registering to exports.
mixin exportToJs! (foo, MainFunction!atStart);Where foo and atStart are extern (C) functions.
Finally, to execute your code from Javascript, you can either use require in a JS file:
// Use relative paths if you haven't made an NPM package yet
const mymodule = require ('./module.node');
console.log (mymodule.foo (1, 3));Or execute directly with node in case you have MainFunctions:
node example.jsIn this example, atStart would be executed.