In node-webkit, is there any way to find the path to the current application? In node.js, you can use __dirname to find the path to the current application, but in node-webkit, the variable __dirname appears to be undefined.

The following node.js script prints the file path correctly:

console.log(__dirname)

The following node-webkit script does not print the file path correctly:

<script type = "text/javascript">
    alert(__dirname);
</script>

What is the correct way to find the path to the current application in node-webkit?

有帮助吗?

解决方案 2

The answer to this question was discussed here: https://groups.google.com/d/topic/node-webkit/IwGzluFC9iU/discussion

On Windows, use "process.execPath" to see the path of the executable that launched it. Then work from there, removing the executable's filename from the path to get the folder's path (assuming your app's .nw is relative to the executable or is combined with it).

This works for me whether it is running with the zipped 'app.nw' or where 'nw.exe' and 'app.nw' are combined into one executable file (app.exe).

其他提示

The accepted answer's link is no longer available, so here is a short answer:

nw.js extract the content of your app, to a temp directory, every time you run it.

If you want to access the path where nw.js extracted your app, use process.cwd()

In other causes, where you want to access the path of your executable app, use:

var path = require('path');
var nwDir = path.dirname(process.execPath);

If you are looking for the path to the App source (i.e. the folder that contains package.json) then you can use process.cwd().

No matter what the environment's true working directory is when the node executable is launched, it will set process.cwd() to the location of the App source. If the App is contained in an archive, cwd will point to the temporary folder where the source is extracted.

Importantly, note that process.cwd() can be changed during the application run by process.chdir(newPath) and potentially by other events as well, so you might want to store the initial value at application launch.

EDIT: Just to clarify, process.cwd() is set to the folder that contains the actual package.json file that is used by the running app. So if you have packaged your app in an archive or executable (zip, exe, nwz, nw, etc), then nw.exe will extract the project files to a temporary directory before running the app. So process.cwd() will point to that temporary folder, not the location of the original archive or executable.

this should work:

var nw = require('nw.gui'); //This line is only required for NW.js 0.12.x and below

console.log(nw.__dirname)

window.location won't work if you're loaded an external uri, but the following seems reliable regardless:

var path = require('path');
,appPath = path.dirname(require.main.filename)

Not sure when this is added, but I believe the official way to get the start up path now is:

nw.App.startPath
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top