Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Simple include file #32

Open
turbobuilt opened this issue Jun 21, 2015 · 3 comments
Open

Simple include file #32

turbobuilt opened this issue Jun 21, 2015 · 3 comments

Comments

@turbobuilt
Copy link

Hello,

It would be really nice if there was a simple "include" function to include a js file in a page. Of course there are modules, but sometimes it is nice to be able to include another file for any reason. Currently this can be done in a roundabout way:

function include(f) {
eval.apply(global, [fs.readFileSync(f).toString()]);
}

But this has serious limitations. Using eval makes debugging very difficult. You can't tell which file the error message is coming from. Adding a simple "include" ability for a raw js script would make things much easier.

This addition would significantly increase the flexibility that io.js provides, making it an even more useful tool. My guess is that such an include is considered "bad practice" in node. But let's be honest... Javascript is by nature a flexible language - dynamically typed, contains eval, all the things that stiff programmers hate. It's the nature of the language, and keeping it out doesn't seem to be at the heart of js.

@feross
Copy link
Member

feross commented Jun 21, 2015

Why won't require('./file')() work for you?

@turbobuilt
Copy link
Author

Well, the problem is that require doesn't put things in the global scope. Right now I'm working on a smallish project, but just want to move some utility functions into a separate file. I could always just make a module u for utilities, but it just seems like is a legitimate use-case scenario for a requireGlobal function that includes the requires in the global scope.

@lmntr
Copy link

lmntr commented Jul 28, 2016

Modules are called in their own separate scope. Exports need to be exported in order to be used elsewhere.

Example:

var a = 1;
var b = 2;
exports.a = a;
exports.b = b;

In your other file:

var o = require('./file.js');
console.log(typeof a); // undefined
console.log(typeof b); // undefined
console.log(o.a); // 1
console.log(o.b); // 2

It's kinda similar to making a class in JavaScript, except replace this with exports.

If you want, you can assign the variables directly to global like this:

global.a = 1;
global.b = 2;

I wouldn't recommend this though because it could have conflict with other variables

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants