37

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.

Antrikshy
  • 2,918
  • 4
  • 31
  • 65

1 Answers1

49

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.

Dmitry Matveev
  • 5,320
  • 1
  • 32
  • 43
  • 2
    Plus 1 for the link to the doc – sramzan May 21 '17 at 00:28
  • 4
    Is there a less verbose way of requiring a single file (without the need for 2 lines, path, path.resolve, __dirname, relative paths, etc.)? – Luke Apr 25 '18 at 00:35
  • 4
    While this solution definitely works, the './' (which I was missing) seems to actually work as one would expect now and the `path.resolve( __dirname...` isn't needed anymore – jgreen May 24 '19 at 17:39