Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending or adding functions to modules of Node

Tags:

node.js

I want to add few methods to async package for my project requirements.. I don't want to change js file of aync. How to extend a module of Node to add more functions?

When I do require('myasync') I want all the functions of 'async' module and also the functions that I added.

like image 704
Neeraj Krishna Avatar asked Jul 01 '14 19:07

Neeraj Krishna


1 Answers

The steps in order to complete this would be:

  • Get the module's pre-defined functionality as your own variable
  • Modify, delete, and/or append more functionality to the variable (via Javascript's functional paradigm)
  • Re-export the variable as your own, which allows you to require it (either as an NPM module or as a file module).

First, we require async.

var newModule = require('async');

Now that we've retrieved the module async, we can append our own function.

newModule.betterParallel = function(myParameters) { ... };

Not only can we add our own function, but we can even delete from the module - since it is now our own.

delete newModule['series'];

With that completed, we need to then re-export our new module.

module.exports = newModule;

If you want to publish this to NPM as your own module, you can use npm publish. If you don't want to, you can simply require this file - and now it contains your modified changes.

like image 54
Brendan Avatar answered Sep 30 '22 03:09

Brendan