NodeJS 中 fs-extra 的同步複製
同步複製簡介
此方法以同步方式將檔案或目錄從一個位置複製到另一個位置。該目錄可以包含子目錄和檔案。
語法
copySync(src, dest[, options])
引數
src – 這是一個字串引數,用於儲存需要複製的檔案或目錄的源位置。如果位置是目錄,則會複製目錄中的所有內容,而不是整個目錄。
dest – 用於儲存檔案/目錄將要複製到的目標位置。如果 src 是檔案,則 dest 不能是目錄。
選項
overwrite – 如果設定為 true,則會覆蓋現有的檔案或目錄。預設值為 true。
errorOnExist – 僅當 overwrite 設定為 false 時,如果目標檔案/資料夾存在,則會丟擲錯誤。
preserveTimestamps – 如果為 true,則最新修改和訪問時間將設定為原始檔案的時間,否則將取決於作業系統。
filter – 此選項將過濾複製的檔案。如果設定為 true,則包含過濾的檔案。
由於它是同步複製,因此它沒有回撥函式。
示例 1
在繼續之前,請檢查是否已安裝 fs-extra;如果未安裝,請安裝 fs-extra。
您可以使用以下命令檢查是否已安裝 fs-extra。
npm ls fs-extra
建立一個 syncCopyExample.js 檔案,並將以下程式碼片段複製貼上到該檔案中。
現在,執行以下命令來執行以下程式碼片段。
node syncCopyExample.js
程式碼片段 −
const fs = require('fs-extra')
// copying file in sync process
fs.copySync('/tmp/myfile', '/tmp/mynewfile')
console.log("File copied in Sync")
// Copies directory from src to dest
fs.copySync('/tmp/mydir', '/tmp/mynewdir')
console.log("Directory copied in Sync")輸出
C:\Users\tutorialsPoint\> node syncCopyExample.js File copied in Sync Directory copied in Sync
示例 2(使用 filter 函式)
const fs = require('fs-extra')
// Copying files with .txt or .avi as extension
fs.copySync(
'/tmp/newFile.txt', '/tmp/myfile2.txt', /.*(.txt|.avi)$/,
(err) => { console.log ('An error occured while copying')})
console.log("Successfully copied !")
C:\Users\tutorialsPoint\> node syncCopyExample.js
Successfully copied!
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP