Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js convention for module require variable names

Tags:

node.js

Just about all the Node.js code I’ve seen on the internet uses this convention for requiring modules, where the return value of require is assigned to a variable with the same name as the module:

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

The trouble is that that many module names are quite common words that we would like to use for variable names elsewhere in our code—e.g. var path = path.join(basePath, fileName)—which will probably cause problems due to name shadowing.

Of course, we could choose a different name for the module variable to avoid name clashes (e.g. pathModule or uppercase Path), but that seems to break with the convention. Or we could choose a different name for variables elsewhere in the code—e.g. var thePath = path.join(...). What is most commonly done in this case?

like image 449
Will Avatar asked Oct 31 '22 14:10

Will


1 Answers

Leave the module name as is: It's IMHO common practice in Node.js to refer to the bla module using the variable bla.

Instead, I'd recommend to be more specific with your variable names when it comes to concrete usage, e.g.:

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

You don't do this just for fun, you do this for a specific file for a specific reason. E.g., you want to load a configuration file. Then rename the variable to configurationPath or something like this:

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

Having a variable just named path is quite … well, it doesn't tell you much of the story. Instead, the path module is actually about paths, so it's okay to name it like this.

Hope this helps.

PS: Most probably, even configurationPath is a bad name, but this entirely depends on your situation and what's your intent. I just used it as an example, don't take it literally.

like image 113
Golo Roden Avatar answered Nov 15 '22 12:11

Golo Roden