HelloWorld
HelloWorld

Reputation: 1863

How to add a native C-module to a node project?

I created a node project and for a specific function, I need to create a custom native C-module. I created a Hello World project and moved it into a sub directory of my node project (called my-native-module). It contains the bindings.gyp, the hello-world.c, etc.

How can I now embed this into the project itself without making it an external project? How would I compile this? Is there a specific npm command for this?

Here is the current directory structure of my project, with the native-module inside

+ my-native-module/...
|  - binding.cc
|  - binding.gyp
|  - package.json
|  - package-lock.json
|
+ node_modules/
|  - ...
|  - ...
| 
+ src/
|  - foo1.js
|  - foo2.js
| 
- package.json
- package-lock.json

Upvotes: 2

Views: 596

Answers (1)

Ulises
Ulises

Reputation: 549

First tell npm that you are using gyp by setting "gypfile": true and by adding build and clean commands to scripts in package.json

{
    "name": "application",
    "version": "0.0.1",
    "description": "using gyp",
    "main": "index.js",
    "gypfile": true,
    "scripts": {
        "start": "node src/foo1.js",
        "test": "your test commands",
        "build": "node-gyp rebuild",
        "clean": "node-gyp clean"
    }
}

Then you add the binding.gyp file to the root of your project directory with a content like this:

{
"targets": [
    {
       "target_name": "c_module_name",
       "sources": [
           "my-native-module/binding.cc"
        ]
    }
]

}

run the project with npm start, if its necessary run npm run build to build the c module

now you can import it with

var c_module = require('../build/Release/c_module_name.node');//if it is imported from src/*.js

When deployed npm will handle the gyp building process

now the project is like this:

+ my-native-module/...
|  - binding.cc
|
+ node_modules/
|  - ...
|  - ...
| 
+ src/
|  - foo1.js
|  - foo2.js
| 
- binding.gyp
- package.json
- package-lock.json

Note: c module needs to be written in nodeapi

Upvotes: 2

Related Questions