How to get the current directory for an nw.js executable

2.5k views Asked by At

Struggling to find the current directory when I create an nw.js executable.

I have created a Mac server application with a mix of html and Javascript and a lot of node.js module usage. I have two xml files that the server accesses and that reside in the same folder as the application.

When I run the application as follows: ./nwjs.app/Contents/MacOS/nwjs . and find the current directory as follows: var workingFolder = process.cwd(); then my working folder is the one where the application and xml files reside.

However, if I follow the 'package and distribute' guidelines (create a .nw file, name it app.nw, and put in contents/resources), and then run the .app executable, I get the following as the working folder: /private/var/folders/3x/2hq40kzs59q8gj6yfn4ktj940000gn/T/.io.nwjs.nw.HcwnF2

I assume that the context changed. So I have been looking at alternatives to get the current directory. I tried: var workingFolder = global.__dirname; and got the same result. Then: var workingFolder = process.env.PWD; and got undefined (although this worked for the 'unpackaged' version)

How do I get the current directory?

Any ideas would be much appreciated!

2

There are 2 answers

3
digit On

Node-Webkit extracts the *.nw file to the temporary directory so that temporary directory is the current working directory. You can use side by side packaging (Putting the package.json file and nw.exe in same folder without compressing) method to keep the working directory to the folder where nw and package.json file resides. You can use the following to get the current path

var path = require('path');
var nwPath = process.execPath;
var nwDir = path.dirname(nwPath);
1
Saket Patel On

For Windows use: var path = require('path'); path.dirname(process.execPath);

For Mac and Linux use: global.__dirname;