EDIT
export with ES6 is a bit nicer
export const hello = function(){ console.log('hello'); };
import will look like
import {hello} from './file';
Original answer
Do you want to use module.exports
var hello = function(){ console.log('hello'); }; module.exports = hello;
If you just export one thing, I usually do it all in one line
var hello = module.exports = function() { console.log('hello'); };
Additionally
If you use a named function , if there is an error in the code, your stack trace will be much nicer. Here path I will write it
// use a named function β var hello = module.exports = function hello() { console.log("hello"); };
Now, instead of showing anonymous for the function name in the stack trace, it will show you hello . This makes it easier to find bugs.
I use this template everywhere to easily debug code. Here is another example
// event listeners β mystream.on("end", function onEnd() { console.log("mystream ended"); }; // callbacks β Pokemon.where({name: "Metapod"}, function pokemonWhere(err, result) { // do stuff });
If you want to export several things , you can use exports directly, but you must provide a key
// lib/foobar.js exports.foo = function foo() { console.log("hello foo!"); }; exports.bar = function bar() { console.log("hello bar!"); };
Now when you use this file
var foobar = require("./lib/foobar"); foobar.foo();
As a final bonus, I will show you how you can rewrite this foobar.js to export a single object , but still get the same behavior
// lib/foobar.js module.exports = { foo: function foo() { console.log("hello foo!"); }, bar: function bar() { console.log("hello bar!"); } }; // works the same as before!
This allows you to write modules depending on which method is best for that particular module . Hooray!