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


Node.js fsPromises.copyFile(src, dest[, mode])用法及代碼示例

fsPromises.copyFile(src, dest[, mode])

曆史
版本變化
v14.0.0

將 'flags' 參數更改為 'mode' 並實施更嚴格的類型驗證。

v10.0.0

添加於:v10.0.0


參數
  • src <string> | <Buffer> | <URL> 要複製的源文件名
  • dest <string> | <Buffer> | <URL> 複製操作的目標文件名
  • mode <integer>指定複製操作行為的可可選飾符。可以創建一個由兩個或多個值的按位或組成的掩碼(例如fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE)默認: 0.
    • fs.constants.COPYFILE_EXCL :如果 dest 已存在,則複製操作將失敗。
    • fs.constants.COPYFILE_FICLONE :複製操作將嘗試創建 copy-on-write reflink。如果平台不支持copy-on-write,則使用回退複製機製。
    • fs.constants.COPYFILE_FICLONE_FORCE :複製操作將嘗試創建 copy-on-write reflink。如果平台不支持copy-on-write,則操作將失敗。
  • 返回: <Promise> 成功時以undefined 實現。

異步複製 srcdest 。默認情況下,如果 dest 已經存在,它會被覆蓋。

不保證複製操作的原子性。如果在打開目標文件進行寫入後發生錯誤,將嘗試刪除目標文件。

import { constants } from 'node:fs';
import { copyFile } from 'node:fs/promises';

try {
  await copyFile('source.txt', 'destination.txt');
  console.log('source.txt was copied to destination.txt');
} catch {
  console.log('The file could not be copied');
}

// By using COPYFILE_EXCL, the operation will fail if destination.txt exists.
try {
  await copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL);
  console.log('source.txt was copied to destination.txt');
} catch {
  console.log('The file could not be copied');
}

相關用法


注:本文由純淨天空篩選整理自nodejs.org大神的英文原創作品 fsPromises.copyFile(src, dest[, mode])。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。