Pregunta

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?

¿Fue útil?

Solución

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top