fs-extra 中的 ensureSymlink() 函式 - NodeJS
非同步 ensureSymlink() 簡介
此方法將確保符號連結是否存在。如果不存在,它將建立目錄結構。
語法
createSymlink(srcPath, destPah[, type] [, callback])
引數
srcPath – 檔案的源路徑。
destPath – 檔案的目標路徑。
type – 此引數僅在 Windows 上可用,在其他平臺上被忽略。此引數的可能值為 dir、file 或 junction。
callback – 如果發生任何錯誤,此函式將提供回撥。
示例
在繼續之前,請檢查是否已安裝 fs-extra;如果沒有,請安裝 fs-exra。
您可以使用以下命令檢查 fs-extra 是否已安裝。
npm ls fs-extra
建立一個 **createSymlink.js** 並將以下程式碼片段複製貼上到該檔案中。
現在,執行以下命令來執行以下程式碼片段。
node createSymlink.js
const fs = require('fs-extra')
const srcPath = '/tmp/file.txt'
const destPath = '/tmp/dest/file.txt'
// Creating Symlink with a callback:
fs.ensureSymlink(srcPath, destPath, err => {
console.log(err) // This will return null.
// Successfully created the symlink
})
// Creating Symlink with Promises:
fs.ensureSymlink(srcPath, destPath)
.then(() => {
console.log('success!')
})
.catch(err => {
console.error(err)
})
// Creating Symlink with async/await:
async function createSymlinkExample (src, dest) {
try {
await fs.ensureSymlink(src, dest)
console.log('Success!')
} catch (err) {
console.error(err)
}
}
createSymlinkExample(srcPath, destPath)輸出
C:\Users\tutorialsPoint\> node createSymlinkExample.js
null
{ [Error: EEXIST: file already exists, symlink '/tmp/file.txt' ->
'/tmp/dest/file.txt']
errno: -17,
code: 'EEXIST',
syscall: 'symlink',
path: '/tmp/file.txt',
dest: '/tmp/dest/file.txt' }
{ [Error: EEXIST: file already exists, symlink '/tmp/file.txt' ->
'/tmp/dest/file.txt']
errno: -17,
code: 'EEXIST',
syscall: 'symlink',
path: '/tmp/file.txt',
dest: '/tmp/dest/file.txt' }ensureSymlinkSync() 簡介
此方法還確保符號連結存在。如果不存在,它將建立目錄結構。
語法
createSymlinkSync(srcPath, destPath[, type])
引數
srcPath – 檔案的源路徑。
destPath – 檔案的目標路徑。
type – 此引數僅在 Windows 上可用,在其他平臺上被忽略。此引數的可能值為 dir、file 或 junction。
示例
在繼續之前,請檢查是否已安裝 fs-extra;如果沒有,請安裝 fs-exra。
您可以使用以下命令檢查 fs-extra 是否已安裝。
npm ls fs-extra
建立一個 createSymlinkSyncExample.js 並將以下程式碼片段複製貼上到該檔案中。
現在,執行以下命令來執行以下程式碼片段。
node createSymlinkSyncExample.js
程式碼片段−
const fs = require('fs-extra')
const srcPath = '/tmp/file.txt'
const destPath = '/tmp/dest2/file.txt'
fs.ensureSymlinkSync(srcPath, destPath)
console.log('Success... !')輸出
C:\Users\tutorialsPoint\> node createSymlinkSyncExample.js Success... !
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP