Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to require several modules in NodeJS

I don't much like the standard way to require modules, which goes something like this:

connect = require 'connect'
express = require 'express'
redis = require 'redis'
sys = require 'sys'
coffee = require 'coffee-script'
fs = require 'fs'

It's not exactly DRY. In a modest CoffeeScript server, the require dance takes up a fair chunk of the entire script! I've been toying with the following alternative:

"connect,express,redis,sys,coffee-script,fs"
  .split(',').forEach (lib) -> global[lib] = require lib

Since I haven't seen people try to refactor the standard approach, I thought I'd ask if it seems reasonable to do so, and if so, are there any better ways to do it?

like image 535
mahemoff Avatar asked Aug 31 '11 20:08

mahemoff


People also ask

Why do you need separate modules in NodeJS?

Each module in Node. js has its own context, so it cannot interfere with other modules or pollute global scope. Also, each module can be placed in a separate . js file under a separate folder.

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

Now, I personally find it better to declare all your modules on the top of the file since it: Makes it easier to know when you are requiring a module that has a bug (for example, crashes something) Makes it easier for the reader to know all the dependencies of your module.

For what require () is used in NodeJS?

1) require() In NodeJS, require() is a built-in function to include external modules that exist in separate files. require() statement basically reads a JavaScript file, executes it, and then proceeds to return the export object.


1 Answers

Note that coffee-script isn't a valid identifier, so your code isn't really importing it properly. You can use CoffeeScript's flexible object literals to handle this pretty nicely. I'd also use ?= to avoid unnecessarily re-importing modules. Building off of user211399's answer:

global[id] ?= require name for id, name of {
    "connect", "express", "redis", "sys", coffee: "coffee-script", "fs" }

                                                                    [Compile to JS]

Since I'm allowing you to import with different identifiers in different modules, using the global namespace feels particularly unsafe. I'd import them locally instead, as shown below. Be aware that because this uses eval it might not fail gracefully if you specify an illegal identifier.

eval "#{id} = require(#{JSON.stringify name})" name for id, name of {
    "connect", "express", "redis", "sys", coffee: "coffee-script", "fs" }

                                                                    [Compile to JS]
like image 163
Jeremy Avatar answered Oct 04 '22 06:10

Jeremy