Search code examples
node.jsrequirecommonjs

Node.js require module subfolders


The xml2js module offers additional exports in a script located in 'node_modules/xml2js/lib/processors.js'.

What is the preferred way to require() these?

This doesn't work

var stripPrefix = require('xml2js/lib/processors').stripPrefix;

The following works, but seems unintuitive and looks ugly

var stripPrefix = require('./node_modules/xml2js/lib/processors').stripPrefix;

Solution

  • The correct way to import it would be:

    var stripPrefix = require('xml2js').processors.stripPrefix;

    It's because processors.js is exported as exports.processors in the main file of the library. Just FYI, main file is declared in package.json.