简体   繁体   中英

How can I detect Node app startup folder on macOS?

I am developing a cross-platform NodeJS server/app that is distributed as a prebuilt binary, built with pkg ( https://www.npmjs.com/package/pkg ) for Windows, Mac and Linux.

At start-up, the app should generate a default config.json to the application directory. I'm detecting the current, start-up folder of the app with:

var startUpPath = process.cwd();

and this works on Windows, and Linux, but on macOS this fails and the file is generated to the user's home directory instead.

Further notes on macOS :

  • this works when running the source code with node myApp.js
  • this works when running the binary from command line with ./myApp
  • this fails when myApp is started by double-clicking in the Finder

The root cause seems to be that macOS processes always start in the home directory , not in current directory ...?

I'm sure it's trivial but haven't figured it out.

Any pointers here?

Found a way eventually - in case somebody else is searching for a solution.

// Detect startup folder at pkg runtime
if ( process.pkg ) {
    startUpPath = path.resolve(process.execPath + '/..');
} else {
    startUpPath = process.cwd();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM