在 Node.JS 中使用绝对路径创建相对符号链接

Create relative symlinks using absolute paths in Node.JS

我有一个结构如下的项目:

project-root
├── some-dir
│   ├── alice.json
│   ├── bob.json
│   └── dave.json
└── ...

我想创建如下符号链接:

我选择使用fs.symlink函数:

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

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

所以,我做到了:

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

这将创建 foo 符号链接。但是,由于路径是绝对路径,符号链接也使用绝对路径。

如何使符号链接路径相对于目录(在本例中为 some-dir)?

这将防止重命名父目录或将项目移动到另一台机器时出错。

我看到的肮脏替代方案是使用 exec("ln -s alice.json foo", { cwd: pathToSomeDir }, callback);,但我想避免这种情况并使用 NodeJS API。

那么,如何在 NodeJS 中使用绝对路径创建相对符号链接?

选项 1:使用 process.chdir() 将进程的当前工作目录更改为 projectRoot。然后,提供 fs.symlink().

的相对路径

选项 2:使用 path.relative() 或以其他方式生成符号链接与其目标之间的相对路径。将该相对路径作为第一个参数传递给 fs.symlink(),同时为第二个参数提供绝对路径。例如:

var relativePath = path.relative('/some-dir', '/some-dir/alice.json');
fs.symlink(relativePath, '/some-dir/foo', callback);
const path = require('path');
const fs = require('fs');

// The actual symlink entity in the file system
const source = /* absolute path of source */;

// Where the symlink should point to
const absolute_target = /* absolute path of target */;

const target = path.relative(
    path.dirname(source),
    absolute_target
);

fs.symlink(
    target,   
    source,
    (err) => {

    }
);