在Node-Webkit应用程序外部要求/运行JavaScript [英] Requiring/running JavaScript outside of node-webkit application

查看:80
本文介绍了在Node-Webkit应用程序外部要求/运行JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我具有以下应用程序结构:

Suppose I have the following app structure:

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

其中my-app/是包含package.json 打包应用程序my-app.exemy-app.app的未构建目录.

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

我无法将settings.js与我的应用程序的其余部分打包,因为我希望该文件可由用户编辑,并在启动时加载以配置我的应用程序.此外,我计划允许settings.js驻留在任何位置(例如,在用户的主目录中)并可以从那里加载.

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.

在未构建应用程序时,此方法工作正常.我只有一个相对文件的相对路径,并且像往常一样require()它.但是在构建应用程序时(如果使用 grunt-node-webkit-builder 有所作为),这失败了,我得到了可怕的找不到模块"错误.

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.

我已经搜索了node-webkit Wiki,但是找不到关于此问题的任何信息,我有什么遗漏吗? 从打包的node-webkit应用程序中加载和运行外部JavaScript文件的最佳方法是什么,就像使用require()一样?

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?

推荐答案

我建议您使用应用程序数据路径. 请参见此处

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

一个例子

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);
}

分离代码和配置是一个很好的实践,App.dataPath的目标是用户应用程序数据中的特定于应用程序的文件夹(每个OS都不同).

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.

下一个技巧:我更喜欢使用YAML而不是JSON进行配置或设置,因为它允许您在文件内插入注释.

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

这篇关于在Node-Webkit应用程序外部要求/运行JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆