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


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

fs.linkSync()方法用于同步创建到指定路径的硬链接。即使重命名文件,创建的硬链接仍将指向同一文件。硬链接还具有链接文件的实际文件内容。

用法:

fs.linkSync( existingPath, newPath )

参数:此方法接受上面提到并在下面描述的两个参数:

  • existingPath:它是一个字符串,缓冲区或URL,代表必须将符号链接创建到的文件。
  • newPath:它是一个字符串,缓冲区或URL,代表将在其中创建符号链接的文件路径。

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

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



// Node.js program to demonstrate the 
// fs.linkSync() 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.linkSync(__dirname + "\\example_file.txt", "hardlinkToFile", 'file'); 
  
console.log("\nHard link created\n"); 
console.log("Contents of the hard link created:"); 
console.log(fs.readFileSync('hardlinkToFile', 'utf8'));

输出:

Contents of the text file:
Hello GeeksForGeeks

Hard link created

Contents of the hard link created:
Hello GeeksForGeeks

范例2:本示例创建到文件的硬链接并删除原始文件。仍然可以通过硬链接访问原始文件的内容。

// Node.js program to demonstrate the 
// fs.linkSync() 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.linkSync(__dirname + "\\example_file.txt", "hardlinkToFile", 'file'); 
  
console.log("\nHard link created\n"); 
console.log("Contents of the hard link created:"); 
console.log(fs.readFileSync('hardlinkToFile', 'utf8')); 
  
console.log("\nDeleting the original file"); 
fs.unlinkSync("example_file.txt"); 
  
console.log("\nContents of the hard link created:"); 
console.log(fs.readFileSync('hardlinkToFile', 'utf8'));

输出:

Contents of the text file:
Hello GeeksForGeeks

Hard link created

Contents of the hard link created:
Hello GeeksForGeeks

Deleting the original file

Contents of the hard link created:
Hello GeeksForGeeks

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




相关用法


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