Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js "require" function and parameters

When I do:

lib = require('lib.js')(app) 

is app actually geting passed in?

in lib.js:

exports = module.exports = function(app){} 

Seems like no, since when I try to do more than just (app) and instead do:

lib = require('lib.js')(app, param2) 

And:

exports = module.exports = function(app, param2){} 

I don't get params2.

I've tried to debug by doing:

params = {} params.app = app params.param2 = "test"  lib = require("lib.js")(params) 

but in lib.js when I try to JSON.stringify I get this error:

"DEBUG: TypeError: Converting circular structure to JSON" 
like image 791
user885355 Avatar asked Sep 09 '11 21:09

user885355


People also ask

How do you require a function in NodeJS?

1) require() In NodeJS, require() is a built-in function to include external modules that exist in separate files. require() statement basically reads a JavaScript file, executes it, and then proceeds to return the export object.

Can I use both require and import in NodeJS?

Cases where it is necessary to use both “require” and “import” in a single file, are quite rare and it is generally not recommended and considered not a good practice. However, sometimes it is the easiest way for us to solve a problem. There are always trade-offs and the decision is up to you.

What is meaning of require in NodeJS?

2011-08-26. Node.js follows the CommonJS module system, and the builtin require function is the easiest way to include modules that exist in separate files. The basic functionality of require is that it reads a JavaScript file, executes the file, and then proceeds to return the exports object.

Can you use require in a module?

“Require” is built-in with NodeJSrequire is typically used with NodeJS to read and execute CommonJS modules. These modules can be either built-in modules like http or custom-written modules. With require , you can include them in your JavaScript files and use their functions and variables.


1 Answers

When you call lib = require("lib.js")(params)

You're actually calling lib.js with one parameter containing two properties name app and param2

You either want

// somefile require("lib.js")(params); // lib.js module.exports = function(options) {   var app = options.app;   var param2 = options.param2; }; 

or

// somefile require("lib.js")(app, param2) // lib.js module.exports = function(app, param2) { } 
like image 71
Raynos Avatar answered Sep 26 '22 04:09

Raynos