Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I load multiple files with one require statement?

Tags:

node.js

maybe this question is a little silly, but is it possible to load multiple .js files with one require statement? like this:

var mylib = require('./lib/mylibfiles');

and use:

mylib.foo(); //return "hello from one"

mylib.bar(): //return "hello from two"

And in the folder mylibfiles will have two files:

One.js

exports.foo= function(){return "hello from one";}

Two.js

exports.bar= function(){return "hello from two";}

I was thinking to put a package.json in the folder that say to load all the files, but I don't know how. Other aproach that I was thinking is to have a index.js that exports everything again but I will be duplicating work.

Thanks!!

P.D: I'm working with nodejs v0.611 on a windows 7 machine

like image 333
nico144 Avatar asked May 11 '12 15:05

nico144


People also ask

Why we always require modules at the top of a file can we require modules inside of functions?

In the end requiring that module in a function vs at the top of a module consumes the same amount of memory, but requiring at the top of a module means it will always be ready to go when someone requests that route and you would instead factor that extra 30 minuets into your deployment time, not at 3am in the morning ...

How does node require work?

Node. js follows the CommonJS module system, and the built-in require function is the easiest way to include modules that exist in separate files. The basic functionality of require is that it reads a JavaScript file, executes the file, and then proceeds to return the exports object.


4 Answers

First of all using require does not duplicate anything. It loads the module and it caches it, so calling require again will get it from memory (thus you can modify module at fly without interacting with its source code - this is sometimes desirable, for example when you want to store db connection inside module).

Also package.json does not load anything and does not interact with your app at all. It is only used for npm.

Now you cannot require multiple modules at once. For example what will happen if both One.js and Two.js have defined function with the same name?? There are more problems.

But what you can do, is to write additional file, say modules.js with the following content

module.exports = {
   one : require('./one.js'),
   two : require('./two.js'),
   /* some other modules you want */
}

and then you can simply use

var modules = require('./modules.js');
modules.one.foo();
modules.two.bar();
like image 129
freakish Avatar answered Oct 29 '22 06:10

freakish


I have a snippet of code that requires more than one module, but it doesn't clump them together as your post suggests. However, that can be overcome with a trick that I found.

function requireMany () {
    return Array.prototype.slice.call(arguments).map(function (value) {
        try {
            return require(value)
        }
        catch (event) {
            return console.log(event)
        }
    })
}

And you use it as such

requireMany("fs", "socket.io", "path")

Which will return

[ fs {}, socketio {}, path {} ]

If a module is not found, an error will be sent to the console. It won't break the programme. The error will be shown in the array as undefined. The array will not be shorter because one of the modules failed to load.

Then you can bind those each of those array elements to a variable name, like so:

var [fs, socketio, path] = requireMany("fs", "socket.io", "path")

It essentially works like an object, but assigns the keys and their values to the global namespace. So, in your case, you could do:

var [foo, bar] = requireMany("./foo.js", "./bar.js")
foo() //return "hello from one"
bar() //return "hello from two"

And if you do want it to break the programme on error, just use this modified version, which is smaller

function requireMany () {
    return Array.prototype.slice.call(arguments).map(require)
}
like image 4
Cranite Avatar answered Oct 29 '22 08:10

Cranite


Yes, you may require a folder as a module, according to the node docs. Let's say you want to require() a folder called ./mypack/.

Inside ./mypack/, create a package.json file with the name of the folder and a main javascript file with the same name, inside a ./lib/ directory.

{
  "name" : "mypack",
  "main" : "./lib/mypack.js"
}

Now you can use require('./mypack') and node will load ./mypack/lib/mypack.js.

However if you do not include this package.json file, it may still work. Without the file, node will attempt to load ./mypack/index.js, or if that's not there, ./mypack/index.node.

My understanding is that this could be beneficial if you have split your program into many javascript files but do not want to concatenate them for deployment.

like image 2
chharvey Avatar answered Oct 29 '22 08:10

chharvey


You can use destructuring assignment to map an array of exported modules from require statements in one line:

const requires = (...modules) => modules.map(module => require(module));
const [fs, path] = requires('fs', 'path');
like image 2
Grant Miller Avatar answered Oct 29 '22 06:10

Grant Miller