How do you use a natively compiled Node module in an ES6 module?

Viewed 137

If you are writing an ES6 module to run in NodeJS, how do you import another module that includes natively compiled code?

For example if I set "type": "module" in package.json, do an npm install talib and then try to run this:

import talib from 'talib';

I get this error in Node v16.2.0:

node:internal/process/esm_loader:74
    internalBinding('errors').triggerUncaughtException(
                              ^

TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".node" for node_modules/talib/build/Release/talib.node
    at new NodeError (node:internal/errors:363:5)
    at Loader.defaultGetFormat [as _getFormat] (node:internal/modules/esm/get_format:71:15)
    at Loader.getFormat (node:internal/modules/esm/loader:105:42)
    at Loader.getModuleJob (node:internal/modules/esm/loader:243:31)
    at async ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:75:21)
    at async Promise.all (index 0)
    at async link (node:internal/modules/esm/module_job:80:9) {
  code: 'ERR_UNKNOWN_FILE_EXTENSION'
}

talib is one example but there are a number of others, all of which exhibit the same behaviour. They all seem to be using node-gyp to build.

How can you use these modules in your own ES6 module code? Do the modules like talib and friends need changes? If so, what should be changed and is it backwards compatible?

1 Answers

Surprisingly - this works for me:

/*eslint-disable */
const talib = require("talib")
/*eslint-enable */
Related