4

"Simple" question -- I'm trying to get the path to a directory of a node script, but when I run from a symlinked directory, I keep getting the path to the physical file instead of the path to the symlinked structure. How do I get the symlinked path?

/path/to/symlink --> /path/to/real

/path/to/symlink> node echo.js

# echo.js
console.log( __dirname );     // /path/to/real
console.log( process.cwd() ); // /path/to/real

[edit] Just for clarification of my own sanity:

$ mkdir test
$ cd test
test$ mkdir a
test$ ln -s a b
test$ cd b
b$ node
> process.cwd()
'/test/a'

2 Answers2

6

You can get symlink path through process.env.PWD on OSX.

Windows looks as has no this issue.

Roman Dvornov
  • 131
  • 1
  • 5
  • The directory in which the file is symlinked, and I want the symlinked directory path, not the original directory path. – Aditya Mittal Apr 06 '22 at 23:43
  • PLEASE take a look at [this answer](https://stackoverflow.com/a/31436403/177710) on the limits of using `process.env.PWD` - in short, it never changes once a script has started to run. – Oliver Jan 03 '23 at 10:43
2
const { execSync } = require('child_process');

execSync('pwd').toString()

Running pwd as a child process returns the current directory with symlinks.

Oliver
  • 9,239
  • 9
  • 69
  • 100
SubHero
  • 51
  • 3