Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to require a file in node.js and pass an argument in the request method, but not to the module?

Tags:

I have a module.js that must be loaded; In order to work needs objectX;

How do I pass the objectX to the module.js in the require method provided by node.js?

thanks

// my module.js objectX.add('abc'); // error: objectX is undefined 

I would like a way to do it, without having to change all my classes because would take a lot of time... and they way it is has good performance for the client side. (I mix clientfiles with serverfiles***)

like image 321
Totty.js Avatar asked Jan 12 '12 11:01

Totty.js


People also ask

How do I use require in NodeJS?

You can think of the require module as the command and the module module as the organizer of all required modules. Requiring a module in Node isn't that complicated of a concept. const config = require('/path/to/file'); The main object exported by the require module is a function (as used in the above example).

Which object holds all arguments passed after executing a script with the Node command?

In Node. js, as in C and many related environments, all command-line arguments received by the shell are given to the process in an array called argv (short for 'argument values'). There you have it - an array containing any arguments you passed in.

How can you make properties and methods available outside the module file in NodeJS?

The exports keyword is used to make properties and methods available outside the module file.


1 Answers

The module that you write can export a single function. When you require the module, call the function with your initialization argument. That function can return an Object (hash) which you place into your variable in the require-ing module. In other words:

main.js

var initValue = 0; var a = require('./arithmetic')(initValue); // It has functions console.log(a); // Call them console.log(a.addOne()); console.log(a.subtractOne()); 

arithmetic.js:

module.exports = function(initValue) {   return {     addOne: function() {       return initValue + 1;     },     subtractOne: function() {       return initValue - 1;     },   } } 
like image 171
kgilpin Avatar answered Oct 13 '22 15:10

kgilpin