Question

I'm building an modular app and have a configuration file to include different modules depending on user preferences.

Normally I'd do something like

var fs = require('fs');

but I'm taking the required modules from an array, so for each require I have a script object that looks like this

{
   name:'fs',
   file:'fs',
   isGlobal:true
}

then I'm dynamically requesting the module with

window[script.name] = require(script.file);

this works fine if I check for window.fs. However, other modules that rely on fs will call just fs.

I know window.fs and fs should both resolve, but in node-webkit, they aren't.

I'm trying to figure out a way to include the var name as a global directly.

Of course, I can't use var script.name = require(script.file); as that would set the script.name value, not a global variable.

Any suggestions on this?

Was it helpful?

Solution 2

Note: it's been a few versions since I've last used node-webkit, but I think the below is still accurate. I tend to abbreviate node-webkit to nw, if that's okay. :)

I know window.fs and fs should both resolve, but in node-webkit, they aren't.

In nw, global is the global object, while each nw window has it's own window object (unless you fork nw). This may be a lil bit confusing, since using the nw devtools to create a global will actually create a property on window as expected, so it's not unreasonable to assume you can create globals the same way as in a browser. However, that's really just a side-effect of the devtools running in nw's window context.

However, code running in nw's module context does not even have access to window but can, of course, access global normally.

This is documented here. The first three paragraphs specifically deal with your issue. In short, you'll want to be sure which context your code is running in.

Node's globals meanwhile have a (brief) description here.

OTHER TIPS

You can refer to global in cross env way:

var global = new Function("return this")();
global.fs = require('fs');

Then at any point you can refer to fs module via simple global fs variable, and in browser environment global would be window.

Still, you should reconsider your approach. As above is very poor way to work with CJS style. One of the beauties of CJS is that it allows you not to rely on global scope, and you go against that, which raise issues.

Other thing, it's a bad practice to resolve paths passed to require dynamically. In modules that we'll have soon with ES6 it won't be possible, you should always use plain strings, and it's good practice to follow with CJS as well. It would be more future bulletproof if you generate script that injects plain strings to requires.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top