當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Node.js fs.readlinkSync()用法及代碼示例

fs.readlinkSync()方法是fs模塊的內置應用程序編程接口,用於同步返回符號鏈接的值,即其鏈接到的路徑。可選參數可用於指定鏈接路徑的字符編碼。

用法:

fs.readlinkSync( path, options )

參數:此方法接受上述和以下所述的兩個參數:



  • path:它是一個字符串,緩衝區或URL,代表符號鏈接的路徑。
  • options:它是一個對象或字符串,可用於指定將影響輸出的可選參數。它具有一個可選參數:
    • encoding:它是一個字符串值,它指定返回鏈接路徑的字符編碼。默認值為“ utf8”。

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

範例1:

// Node.js program to demonstrate the 
// fs.readlinkSync() method 
  
// Import the filesystem module 
const fs = require('fs'); 
  
// Create a symbolic link 
fs.symlinkSync(__dirname + "\\example_file.txt", 
         "symlinkToFile", 'file'); 
  
console.log("\nSymlink created\n"); 
  
// Get the path of the symbolic link 
symlinkPath = fs.readlinkSync("symlinkToFile"); 
console.log("Path of the symlink:", symlinkPath);

輸出:

Symlink created

Path of the symlink:G:\tutorials\nodejs-fs-readlinkSync\example_file.txt

範例2:本示例創建到目錄的符號鏈接。

// Node.js program to demonstrate the 
// fs.readlinkSync() method 
  
// Import the filesystem module 
const fs = require('fs'); 
  
// Create a symbolic link 
fs.symlinkSync(__dirname +  
    "\\example_directory", "symlinkToDir", 'dir'); 
  
console.log("\nSymlink created\n"); 
  
// Get the path of the symbolic link 
symlinkPath = fs.readlinkSync("symlinkToDir"); 
console.log("Path of the symlink:", symlinkPath);

輸出:

Symlink created

Path of the symlink:G:\tutorials\nodejs-fs-readlinkSync\example_directory

參考: https://nodejs.org/api/fs.html#fs_fs_readlinksync_path_options




相關用法


注:本文由純淨天空篩選整理自sayantanm19大神的英文原創作品 Node.js | fs.readlinkSync() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。