1

I have multiple js files, all have the same requires in the beginning like

var config = require("config");
var expect = require("chai").expect;

var commonAssertions = require('../../../utils/common_assertions.js');
var commonSteps = require('../../../utils/common_steps.js');

I am thinking about putting all of them in one file and just require this single file.

I am wondering if there is any best practice or convention on this in nodejs.

ccy
  • 1,385
  • 6
  • 17
  • 27

1 Answers1

1

Remember that require() must always return a Javascript object, module.exports.

So if you were to extract this to a different file, that would be perfectly fine.

includes.js

exports.config =  require("config");
exports.chai = require("chai").expect;

exports.commonAssertions = require('../../../utils/common_assertions.js');
exports.commonSteps = require('../../../utils/common_steps.js');

myfile.js

includes = require('./includes')
includes.expect(true).to.be.true //For example

It is not necessarily a good or bad practice. I would say that if you expect to need the exact same modules from many different files, then go for it.

Brandon Horst
  • 1,921
  • 16
  • 26
  • Thanks. So is there any way to put all includes in one file, but still use `expect(true).to.be.true` instead of `includes.expect(true).to.be.true`? – ccy Jun 12 '14 at 19:01
  • 1
    Nope! Not without doing something horrible with prototypes at least. And you wouldn't want that. That would be namespace pollution and would go against some fundamental node principles. It's better to always be very explicit about exactly where any function you are calling comes from. – Brandon Horst Jun 12 '14 at 19:03
  • Memory and performance-wisely doesn't it make a difference? In one case a file is read several time, variable loaded content several time, instead of once? – Augustin Riedinger Mar 23 '15 at 17:45
  • Also that means that the result coming from `require(filename)` has to be constant. Is that also a best practice from NodeJS? Imagine a library that would return an attribute `instanciatedAt: new Date()`... – Augustin Riedinger Mar 23 '15 at 18:02