📜  Node.js fs.symlink()函数

📅  最后修改于: 2022-05-13 01:56:34.761000             🧑  作者: Mango

Node.js fs.symlink()函数

fs.symlink() 方法用于创建指向指定路径的符号链接。这将创建一个链接,使path指向target 。相对目标相对于链接的父目录。

句法:

fs.symlink( target, path, type, callback )

参数:此方法接受上面提到的四个参数,如下所述:

  • 目标:它是一个字符串、缓冲区或 URL,表示必须创建符号链接的路径。
  • path:它是一个字符串、缓冲区或 URL,表示将创建符号链接的路径。
  • type:它是一个字符串,表示要创建的符号链接的类型。它可以用'file'、'dir'或'junction'指定。如果目标不存在,将使用“文件”。
  • callback:方法执行时调用的函数。
    • err:如果操作失败将抛出的错误。

下面的示例说明了 Node.js 中的fs.symlink() 方法

示例 1:此示例创建文件的符号链接。

// Node.js program to demonstrate the
// fs.symlink() method
  
// Import the filesystem module
const fs = require('fs');
  
console.log("Contents of the text file:");
console.log(fs.readFileSync('example_file.txt', 'utf8'));
  
fs.symlink(__dirname + "\\example_file.txt",
        "symlinkToFile", 'file', (err) => {
  if (err)
    console.log(err);
  else {
    console.log("\nSymlink created\n");
    console.log("Contents of the symlink created:");
    console.log(fs.readFileSync('symlinkToFile', 'utf8'));
  }
})

输出:

Contents of the text file:
Hello Geeks

Symlink created

Contents of the symlink created:
Hello Geeks

示例 2:此示例创建指向目录的符号链接。

// Node.js program to demonstrate the
// fs.symlink() method
  
// Import the filesystem module
const fs = require('fs');
  
fs.symlink(__dirname + "\\example_directory",
           "symlinkToDir", 'dir', (err) => {
  if (err)
    console.log(err);
  else {
    console.log("Symlink created");
    console.log("Symlink is a directory:",
       fs.statSync("symlinkToDir").isDirectory()
    );
  }
});

输出:

Symlink created
Symlink is a directory: true

参考: https://nodejs.org/api/fs.html#fs_fs_symlink_target_path_type_callback