当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Node.js fs.symlinkSync()用法及代码示例


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

用法:

fs.symlinkSync( target, path, type )

参数:此方法接受上述和以下所述的三个参数:



  • target:它是一个字符串,缓冲区或URL,代表必须创建符号链接的路径。
  • path:它是一个字符串,缓冲区或URL,代表将在其中创建符号链接的路径。
  • type:它是一个字符串,代表要创建的符号链接的类型。可以用“文件”,“目录”或“连接”指定。如果目标不存在,将使用“文件”。

以下示例说明了Node.js中的fs.symlinkSync()方法:

范例1:本示例创建到文件的符号链接。

// Node.js program to demonstrate the 
// fs.symlinkSync() 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.symlinkSync(__dirname + "\\example_file.txt", 
               "symlinkToFile", 'file'); 
  
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.symlinkSync() method 
  
// Import the filesystem module 
const fs = require('fs'); 
  
fs.symlinkSync(__dirname + "\\example_directory", 
               "symlinkToDir", 'dir'); 
  
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_symlinksync_target_path_type




相关用法


注:本文由纯净天空筛选整理自sayantanm19大神的英文原创作品 Node.js | fs.symlinkSync() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。