Write Your Own Node Modules

As you write more and more complicated code, it helps to be able to break it up into smaller units. This is pretty easy in Node.

Here's an example:

module.exports = {  
    some_function: () => console.log('This console.log brought to you by some module. :P ')

None of the code in a module is visible outside it except what you put in module.exports. You can make it an object or a function, Node is fine with either.

If you were to save this code in a file called some_module.js you could use it from another file like so:

var some_module = require('./some_module')  

If you saved this second snippet as, say, index.js and ran it, you'd get the following output:

This console.log brought to you by some module. :P  

If we'd written require('some_module'), Node would have looked for our module in the node_modules folder. ./some_module tells Node that the module is in the same directory as index.js. If you'd put ./some_directory/some_module, Node would have looked for some_module in the some_directory directory.

Pretty simple right?

Looking for a software developer?