fs.writeFile(file, data[, options], callback)
| 版本 | 變化 | 
|---|---|
| v18.0.0 | 將無效回調傳遞給   | 
| v17.8.0 | 不推薦將具有自己的   | 
| v16.0.0 | 如果返回多個錯誤,則返回的錯誤可能是   | 
| v15.2.0、v14.17.0 | options 參數可能包含 AbortSignal 以中止正在進行的 writeFile 請求。  | 
| v14.12.0 | 
  | 
| v14.0.0 | 
  | 
| v10.10.0 | 
  | 
| v10.0.0 | 
  | 
| v7.4.0 | 
  | 
| v7.0.0 | 
  | 
| v5.0.0 | 
  | 
| v0.1.29 | 添加於:v0.1.29  | 
參數
file<string> | <Buffer> | <URL> | <integer> 文件名或文件說明符data<string> | <Buffer> | <TypedArray> | <DataView> | <Object>options<Object>|<string>encoding<string> | <null> 默認:'utf8'mode<integer> 默認:0o666flag<string>參看支持文件係統flags.默認:'w'.signal<AbortSignal> 允許中止 in-progress writeFile
callback<Function>err<Error> | <AggregateError>
當file 是文件名時,異步將數據寫入文件,如果文件已存在則替換該文件。 data 可以是字符串或緩衝區。
當file 是文件說明符時,行為類似於直接調用fs.write()(推薦)。請參閱下麵有關使用文件說明符的說明。
如果 data 是緩衝區,則忽略 encoding 選項。
mode 選項僅影響新創建的文件。有關詳細信息,請參閱 。fs.open() 
import { writeFile } from 'node:fs';
import { Buffer } from 'node:buffer';
const data = new Uint8Array(Buffer.from('Hello Node.js'));
writeFile('message.txt', data, (err) => {
  if (err) throw err;
  console.log('The file has been saved!');
});
如果options 是字符串,則它指定編碼:
import { writeFile } from 'node:fs';
writeFile('message.txt', 'Hello Node.js', 'utf8', callback);
在同一個文件上多次使用fs.writeFile()而不等待回調是不安全的。對於這種情況,建議使用 。fs.createWriteStream() 
類似於fs.readFile - fs.writeFile 是一種方便的方法,它在內部執行多個 write 調用以寫入傳遞給它的緩衝區。對於性能敏感的代碼,請考慮使用   。fs.createWriteStream() 
可以使用  <AbortSignal>  取消 fs.writeFile() 。取消是"best effort",可能還有一些數據需要寫入。
import { writeFile } from 'node:fs';
import { Buffer } from 'node:buffer';
const controller = new AbortController();
const { signal } = controller;
const data = new Uint8Array(Buffer.from('Hello Node.js'));
writeFile('message.txt', data, { signal }, (err) => {
  // When a request is aborted - the callback is called with an AbortError
});
// When the request should be aborted
controller.abort();
中止正在進行的請求不會中止單個操作係統請求,而是執行內部緩衝fs.writeFile。
相關用法
- Node.js fs.writeFile()用法及代碼示例
 - Node.js fs.writeFileSync()用法及代碼示例
 - Node.js fs.writeSync()用法及代碼示例
 - Node.js fs.write()用法及代碼示例
 - Node.js fs.watchFile(filename[, options], listener)用法及代碼示例
 - Node.js fs.watchFile()用法及代碼示例
 - Node.js fs.watch()用法及代碼示例
 - Node.js fs.watch(filename[, options][, listener])用法及代碼示例
 - Node.js fs.filehandle.datasync()用法及代碼示例
 - Node.js fs.chmod()用法及代碼示例
 - Node.js fs.read()用法及代碼示例
 - Node.js fs.Dirent.isFile()用法及代碼示例
 - Node.js fs.Dir.closeSync()用法及代碼示例
 - Node.js fs.fchmodSync()用法及代碼示例
 - Node.js fs.symlink(target, path[, type], callback)用法及代碼示例
 - Node.js fs.constants用法及代碼示例
 - Node.js fs.mkdir()用法及代碼示例
 - Node.js fs.mkdirSync()用法及代碼示例
 - Node.js fs.fdatasync()用法及代碼示例
 - Node.js fs.Dirent.isFIFO()用法及代碼示例
 - Node.js fs.copyFile()用法及代碼示例
 - Node.js fs.symlink()用法及代碼示例
 - Node.js fs.truncate()用法及代碼示例
 - Node.js fs.openSync()用法及代碼示例
 - Node.js fs.filehandle.write()用法及代碼示例
 
注:本文由純淨天空篩選整理自nodejs.org大神的英文原創作品 fs.writeFile(file, data[, options], callback)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
