Search code examples
node.jsmodulepathrequireabsolute

Absolute path to file throws error?


Recently I started with NodeJS and I found the require() function.

I have two JS files: main.js in C:/Users/Admin folder and, test.js in F: drive

Here is my test.js file:

function log(name) {
    console.log(name);
}
module.exports.log = log;

and here is my main.js file:

var myModule = require("/F:/test");
myModule.log("Anonymous");

But when I type... C:\Users\Admin>node main.js in Node.js CMD, I get the following error statement:

Error: Cannot find module '/F:/test'

Help me to figure out the error!


Solution

  • You are giving the path of the file wrong.

    It should be F:/test instead of /F:/test.

    You can use path module to resolve the path by path.resolve and check what it resolves to. In your case it is resolving to C:\F:\test.

    Update

    You can check to what your provided path resolves to like below

    const path = require('path');
    let p = path.resolve('/F:/test');
    console.log(p);// C:\F:\test