Node.js module requires variable names

Almost all Node.js code I've seen on the web uses this convention for module requests, where the return value require

is assigned to a variable with the same name as the module:

var path = require('path');
var url = require('url');

      

The problem is that a lot of module names are fairly common words that we would like to use for variable names elsewhere in our code. var path = path.join(basePath, fileName)

, which is likely to cause problems because of the name shading.

Of course, we could have chosen a different name for the module variable to avoid naming conflicts (eg, pathModule

or uppercase Path

), but that seems to break the convention. Or we could choose a different name for the variables elsewhere in the code. var thePath = path.join(...)

... What is most often done in this case?

+3


source to share


1 answer


Leave the module name as is: It is IMHO common practice in Node.js to refer to a module bla

using a variable bla

.

Instead, I would recommend using your variable names more specifically when it comes to specific use, for example:

var path = path.join(basePath, fileName);

      

You are not doing this just for fun, you are doing this for a specific file for a specific reason. For example, you want to load a config file. Then rename the variable to configurationPath

or something like this:



var configurationPath = path.join(basePath, fileName);

      

Having a variable named is path

pretty ... well, that doesn't tell you much. Instead, the module path

is actually about path

s, so it can be called like this.

Hope it helps.

PS: Most likely even configurationPath

- it's a bad name, but it depends entirely on your situation and your intentions. I just used it as an example, I don't take it literally.

+1


source







All Articles