2

Suppose I have the following app structure:

outer-folder/
├── my-app/
└── settings.js

where my-app/ is either the unbuilt directory that contains package.json or the packaged application my-app.exe or my-app.app.

I cannot package settings.js with the rest of my app, because I want this file to be editable by users, and loaded upon startup to configure my app. Moreover, I plan to allow settings.js to reside anywhere (for example, in the user's home directory) and be loadable from there.

This works fine when the app is unbuilt. I just have a relative path to the file and require() it like usual. But when the app is built (with grunt-node-webkit-builder if that makes a difference) this fails and I get the dreaded "Cannot find module" error.

I've searched the node-webkit wiki but can't find anything about this issue, am I missing something? What is the best way to load and run an external JavaScript file, like one would do with require(), from a packaged node-webkit app?

1 Answer 1

1

I suggest you to use the application data path. See the documentation here

An exemple

var gui = require('nw.gui');
var path = require('path');
var yaml = require('js-yaml');
var fs = require('fs');

var confPath = path.join(gui.App.dataPath, 'conf', "dev-conf.yml");
try {
  conf = yaml.load(fs.readFileSync(confPath, 'utf-8'));
} catch (err) {
  throw new Error("Cannot read or parse configuration file '"+confPath+"': "+err);
}

It's a good pratice to separate code and configuration, and App.dataPath aims at the application specific folder in user's application data (different for each OS).

I generally use an installer to copy my configuration file into it.

Next tip: I prefer using YAML instead of JSON for my configuration or settings, because it allows you to insert comments inside the file.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for the answer, the application data path is what I ended up using. However, I did something a bit different...rather than using an installer, I check for the required files in the data path upon app startup and copy over an internal version if they're not there. Thanks also for the YAML suggestion, I'll look into it!
When i do var gui = require('nw.gui'); in my server.js i get ` Cannot find module 'nw.gui'` despite the fact that i am using nwjs to launch the app
Can you reference images and other stuff from an external folder using css?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.