Node.js cannot require a .js file in the same directory

Antrikshy picture Antrikshy · Oct 11, 2014 · Viewed 25.8k times · Source

I have a node-webkit project with a main.js. At the very top, I have

var updater = require("./updater.js");

and I have a file named updater.js in the same directory as main.js. When I run the app, I get the error

Uncaught Error: Cannot find module './updater.js' 

updater.js has one line in it:

module.exports = "Hello!";

I have no idea why it cannot require the file. I have seen another project do the same thing. I can require regular npm modules just fine from the same main.js.

Answer

Dmitry Matveev picture Dmitry Matveev · Oct 11, 2014

This is because, when you run you app (main.js) using node-webkit the root (working) directory is where the index.html is in, so './' refers to that directory not the one in which the file you requesting the module from is in.

You can easily solve this problem by using resolve method in 'path' node module and provide the output from it to the require method in your working file

Simply do the following:

var path = require('path');
var updater = require( path.resolve( __dirname, "./updater.js" ) );

EDIT : info on global node object '__dirname' (and others) can by found here.