title: Create relative symlinks using absolute paths in Node.JS
body: <p>I have a projects with the following structure:</p>
  
  <pre><code>project-root
  ├── some-dir
  │   ├── alice.json
  │   ├── bob.json
  │   └── dave.json
  └── ...
  </code></pre>
  
  <p>I want to create symlinks like the following ones:</p>
  
  <ul>
  <li><code>foo</code> -> <code>alice.json</code></li>
  </ul>
  
  <p>I chose to use the <a href="https://nodejs.org/api/fs.html#fs_fs_symlink_srcpath_dstpath_type_callback" rel="noreferrer"><code>fs.symlink</code></a> function:</p>
  
  <blockquote>
    <h3><code>fs.symlink(srcpath, dstpath[, type], callback)</code></h3>
    
    <p>Asynchronous symlink(2). No arguments other than a possible exception are given to the completion callback. The <code>type</code> argument can be set to <code>'dir'</code>, <code>'file'</code>, or <code>'junction'</code> (default is <code>'file'</code>) and is only available on Windows (ignored on other platforms). Note that Windows junction points require the destination path to be absolute. When using <code>'junction'</code>, the destination argument will automatically be normalized to absolute path.</p>
  </blockquote>
  
  <p>So, I did:</p>
  
  <pre><code>require("fs").symlink(
    projectRoot + "/some-dir/alice.json"
  , projectRoot + "/some-dir/foo"
  , function (err) { console.log(err || "Done."); }
  );
  </code></pre>
  
  <p>This creates the <code>foo</code> symlink. However, since the paths are absolute the symlink uses absolute path as well.</p>
  
  <p>How can I make the symlink path relative to a directory (in this case to <code>some-dir</code>)?</p>
  
  <p>This will prevent errors when the parent directories are renamed or the project is moved on another machine.</p>
  
  <p>The dirty alternative I see is using <code>exec("ln -s alice.json foo", { cwd: pathToSomeDir }, callback);</code>, but I would like to avoid that and use the NodeJS API.</p>
  
  <p>So, how can I make relative symlinks using absolute paths in NodeJS?</p>