Can't find module only first time

I'm using node-webkit engine for my desktop app. This is a structure of my files:

app/
|- scripts/
   |- librecraft.js
|- index.html
|- package.json
|- libre.js

app/index.html

<!DOCTYPE html>
<!-- .... -->
<script>var libre = require('./libre.js');</script>
<script src="scripts/librecraft.js"></script>

app/scripts/librecraft.js

libre.doSomething();

app/libre.js

exports.doSomething = function () { return 42 };

The problem

When I run nw.exe and open app/index.html from it, node-webkit can't find module ./libre.js. But when I refresh (with the right refresh button) it magically works. Why?

If you wonder why it works when you refresh the page, you have to know that your nodejs files are loaded once for the whole life-time of the app. While the app is up, change the returned value (doSomething) to something else, save the file and refresh the page; you will notice that the returned value is the old one.

It seems your node.js file has not been loaded when you call it. Open the dev console and check out the error message (if any).

I would recommend to update your librecraft.js as follows:

//librecraft.js
var libre = require('../libre.js');
var val = libre.doSomething(); //
console.log(val);

Hope this help.

  • It's better not to include or write scripts in the HTML directly, when you use node.js functions. Also, the disadvantage of this technic is, the script (from which you might want to do some background tasks) will reload everytime you reload the page.
  • Use 'node-main' instead. Here: https://github.com/rogerwang/node-webkit/wiki/node-main
  • A simple thing to keep in mind: A node-webkit app is not a website :)