Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to emulate "window" object in Nodejs?

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
like image 946
Ngoc Dao Avatar asked Jan 22 '13 05:01

Ngoc Dao


People also ask

Can we use window object in node JS?

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.

How do I read a directory in node JS?

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.

How do you fix ReferenceError window is not defined?

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.


Video Answer


2 Answers

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

like image 145
THEOS Avatar answered Oct 11 '22 14:10

THEOS


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.

like image 27
Akhil Raina Avatar answered Oct 11 '22 13:10

Akhil Raina