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


Node.js fs-extra ensureLinkSync()用法及代碼示例

ensureLinkSync()函數是ensureLink()的同步版本。該函數確保兩個給定文件之間的鏈接存在。源文件必須已經存在,否則該函數將引發錯誤。如果目標文件的目錄結構不存在,則該函數將創建該目錄結構,並將在源文件和目標文件之間建立鏈接。也可以使用createLinkSync()代替ensureLinkSync()。

用法:

ensureLinkSync(srcPath, destPath)
// OR
createLinkSync(srcPath, destPath)

參數:

  • srcPath:它是一個字符串,其中包含要與另一個文件鏈接的文件的路徑。
  • destPath:它是一個字符串,其中包含另一個文件的路徑,該文件將鏈接到srcPath中指定的文件。

返回值:它不返回任何東西。

請按照以下步驟實現該函數:

  1. 可以使用以下命令安裝該模塊。
    npm install fs-extra
  2. 安裝模塊後,可以使用此命令檢查已安裝模塊的版本。
    npm ls fs-extra

  3. 使用以下命令創建一個名為index.js的文件,並在文件中需要fs-extra模塊。
    const fs = require('fs-extra');
  4. 要運行文件,請在終端中輸入以下命令。
    node index.js

項目結構:項目結構如下所示。

範例1:

index.js


// Requiring module
const fs = require("fs-extra");
  
// source file path
// File needs to exist
const srcPath = "file.txt";
// destination file path
// This file exists already
const destPath = "dest/file.txt";
  
// Function to check
// if destination file
// exists or not
const fileExists = (path) => {
  if (fs.existsSync(path)) return "Destination file exists";
  return "Destination file do not exists";
};
  
// Before function call
const before = fileExists(destPath);
console.log(`Before function call ${before}`);
  
// Function Call
fs.ensureLinkSync(srcPath, destPath);
  
// After function call
const after = fileExists(destPath);
console.log(
  `After function call ${after} and Link is successfully established!!`
);

輸出:

範例2:

Javascript


// Requiring module
const fs = require("fs-extra");
  
// source file path
// File needs to exist
const srcPath = "file.txt";
// destination file path
// This file do not exists
// so it will be created
// bt function
const destPath = "destination/dest/file.txt";
  
// Function to check
// if destination file
// exists or not
const fileExists = (path) => {
  if (fs.existsSync(path)) return "Destination file exists";
  return "Destination file do not exists";
};
  
// Before function call
const before = fileExists(destPath);
console.log(`Before function call ${before}`);
  
// Function Call
fs.ensureLinkSync(srcPath, destPath);
  
// After function call
const after = fileExists(destPath);
console.log(
  `After function call ${after} and Link is successfully established!!`
);

輸出:

參考:https://github.com/jprichardson/node-fs-extra/blob/HEAD/docs/ensureLink-sync.md


相關用法


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