I am learning node.js
for example, I try
var server = require("./myserver.js");
and
var server = require("./myserver");
why do both work? What is this kind of things call?
I am learning node.js
for example, I try
var server = require("./myserver.js");
and
var server = require("./myserver");
why do both work? What is this kind of things call?
If you take a look at node's source code for the require-function, you can see that require's load-function calls a function findLongestRegisteredExtension to determine the file-extension. This function returns .js as its default value if no extension could be determined:
function findLongestRegisteredExtension(filename) {
const name = path.basename(filename);
let currentExtension;
let index;
let startIndex = 0;
while ((index = name.indexOf('.', startIndex)) !== -1) {
startIndex = index + 1;
if (index === 0) continue; // Skip dotfiles like .gitignore
currentExtension = name.slice(index);
if (Module._extensions[currentExtension]) return currentExtension;
}
return '.js';
}
That's why using both require("./myserver.js"); or require("./myserver"); will resolve the same module.