When running in a browser, everything attached to the "window" object will automatically become global object. How can I create an object similar to that in Nodejs?
mySpecialObject.foo = 9;
var f = function() { console.log(foo); };
f(); // This should print "9" to console
In the Node. js module system, each file is treated as a separate module. The Global objects are available in all modules. While in browsers, the global scope is the window object, in nodeJS, the global scope of a module is the module itself, so when you define a variable in the global scope of your Node.
The fs. readdir() method is used to asynchronously read the contents of a given directory. The callback of this method returns an array of all the file names in the directory. The options argument can be used to change the format in which the files are returned from the method.
To solve the "ReferenceError: window is not defined" error, make sure to only use the window global variable on the browser. The variable represents a window containing a DOM document and can't be used on the server side (e.g. in Node. js). If you need to define global variables in Node.
If you were to compare the Web Console to Node running in terminal (both Javascript) :
window
<-> global
(Note: GLOBAL is deprecated)
in Web Console : window.wgSiteName
(random to show functionality)
in Node (Terminal): global.url
document
<-> process
(Note: program process running right now)
in Web Console : document.title
in Node (Terminal): process.title
You can use the predefined object global
for that purpose. If you define foo
as a property of the global
object, it will be available in all modules used after that.
For example, in app.js:
var http = require('http');
var foo = require('./foo');
http.createServer(function (req, res) {
//Define the variable in global scope.
global.foobar = 9;
foo.bar();
}).listen(1337, '127.0.0.1');
And in foo.js:
exports.bar = function() {
console.log(foobar);
}
Make sure you don't use the var
keyword as the global
object is already defined.
For documentation, check out http://nodejs.org/api/globals.html#globals_global.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With