Create relative symbolic links using absolute paths in Node.JS

I have projects with the following structure:

project-root β”œβ”€β”€ some-dir β”‚  β”œβ”€β”€ alice.json β”‚  β”œβ”€β”€ bob.json β”‚  └── dave.json └── ... 

I want to create symbolic links, such as the following:

  • foo β†’ alice.json

I decided to use the fs.symlink function:

fs.symlink(srcpath, dstpath[, type], callback)

Asynchronous symbolic link (2). No arguments other than a possible exception are provided for the completion callback. type can be set to 'dir' , 'file' or 'junction' (default is 'file' ) and is only available on Windows (ignored on other platforms). Note that Windows connection points require the destination path to be absolute. When using 'junction' the destination argument will automatically be normalized to an absolute path.

So I did:

 require("fs").symlink( projectRoot + "/some-dir/alice.json" , projectRoot + "/some-dir/foo" , function (err) { console.log(err || "Done."); } ); 

This creates a symbolic link foo . However, since paths are absolute, symlink also uses an absolute path.

How can I make a symlink path relative to a directory (in this case, some-dir )?

This will prevent errors when renaming parent directories or moving a project to another machine.

The dirty alternative I see uses exec("ln -s alice.json foo", { cwd: pathToSomeDir }, callback); but I would like to avoid this and use the NodeJS API.

So, how can I make relative symbolic links using absolute paths in NodeJS?

+7
symlink
source share
1 answer

Option 1: use process.chdir() to change the current working directory of the process to projectRoot . Then specify the relative paths to fs.symlink() .

Option 2: use path.relative() or else create a relative path between your symbolic link and its target. Pass this relative path as the first argument to fs.symlink() , providing an absolute path for the second argument. For example:

 var relativePath = path.relative('/some-dir', '/some-dir/alice.json'); fs.symlink(relativePath, '/some-dir/foo', callback); 
+6
source share

All Articles