Exploring various ways to load files using require().

Versions used below

node 0.10.36

Common usages

If you’ve used node before these are familiar.

Core Module

Load one of node’s built-in modules.

var http = require('http');

Dependency from npm

Load something that’s in node_modules/, which was most likely installed via npm.

$ npm install faye -S
var faye = require('faye');

Relative path

Load a file relative to the current file.

var helper = require('./util/helper.js');

The file extension is optional.

Absolute path

I’ve never used this but it’s possible to load files with an absolute path.

var helper = require('/Users/paul/js/helper.js');

Again, the file extension is optional.

Other usages


Given this directory structure

├── stuff/
│   ├── foo.js
│   ├── bar.js
│   └── index.js
└── main.js

In main.js you could

var stuff = require('./stuff');

and it’d load ./stuff/index.js.

index.js can require the other files in stuff/. This is handy for making a directory sort of act as an embedded module.

One benefit to omitting the file extension in relative path requires is that you can break a large file down into a directory of smaller files without having to update all the require calls.

// this code doesn't know if it's getting ./stuff.js or ./stuff/index.js
var stuff = require('./stuff');

Json file

When you require a json file you get the parse result.

  "colors": ["red", "green", "blue"]
var colors = require('./data.json').colors;

Any file from a dependency

If you’re okay with relying on a module’s internal file structure, you can require any file from it.

$ npm install <module> -S
var something = require('<module>/lib/something');

This allows you to programmatically determine a module’s version.

var gulpVersion = require('gulp/package.json').version;