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
相關用法
- Node.js console.timeLog()用法及代碼示例
- Node.js fs.fsyncSync()用法及代碼示例
- Node.js GM charcoal()用法及代碼示例
- Node.js GM blur()用法及代碼示例
- Node.js GM sharpen()用法及代碼示例
- Node.js GM drawLine()用法及代碼示例
- Node.js GM drawArc()用法及代碼示例
- Node.js GM drawPolyline()用法及代碼示例
注:本文由純淨天空篩選整理自sayantanm19大神的英文原創作品 Node.js | fs. linksync() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。