node.js use modules without assigning them to variables

Viewed 167

In node.js, I have to put a stem in front of my module before I can call anything in it:

const example = require('example.js');
example.func();

I have a really messy node.js file and I would like to break it up into several pieces. However, my code looks something like this:

function func1(){ /* ... */ }
function func2(){ /* ... */ }

//blah blah
func1();
//blah blah    
func2();

If I split this up into file1.js and file2.js, my code would need to look like this:

var file1 = require('file1.js');
var file2 = require('file2.js');

//blah blah
file1.func1();
//blah blah
file2.func2();

I have to put file1 or file2 before my function to call it, which is something I would like to avoid. Is it possible to not have these stems?

Clarification I want multiple functions per file. The example just uses 1 function per file as an example.

1 Answers

It sounds like you want each export to export just the function, rather than an object containing the function. In file1 and file2, do:

module.exports = function func1() {
};

instead of

module.exports.func1 = function func1() {
};

And then you can call the functions like:

var func1 = require('file1.js');
var func2 = require('file2.js');

//blah blah
func1();
//blah blah
func2();

(it would probably make sense to rename the filenames to func1.js and func2.js as well)

Related