Skip to content Skip to sidebar Skip to footer

Nodejs: Can You Pass A Variable To 'require'?

EDIT: to be clear, the code below has been simplified to focus on the problem at hand. I do know that window does not 'exist' in Node. This code is in fact used with jsdom for offl

Solution 1:

can you pass a variable to 'require'?

No.

I am new to Node and I am probably missing something regarding variables' scope. I thought an inner function had access to the outer function's parameters.

var t = function(window, document){
  varChart = require('chart.js');
}

var t2 = function(){
  varwindow = {};
  vardocument = {};
  t(window, document);
}

t2();

It does, but the code you're bringing in via require isn't in the t or t2 function above.

While you could create global window and document properties before doing the require:

global.window = /*...*/;global.document = /*...*/;

...that would be a Bad Thing™ on two levels:

  1. Your require call isn't necessarily the one that loads the chart.js module.

  2. Globals are, you know, icky. That's the technical term.

Instead, have chart.js expose an initialization function. Then you get that, call it with the required dependencies, and you're all set.


Note: NodeJS has no UI. If you're trying to do some kind of offline rendering, you may need a full headless browser like PhantomJS or similar, rather than NodeJS.

Post a Comment for "Nodejs: Can You Pass A Variable To 'require'?"