fs.writeFile()方法用於將指定的數據異步寫入文件。默認情況下,文件將被替換(如果存在)。 “ options”參數可用於修改方法的函數。
用法:
fs.writeFile( file, data, options, callback )
參數:此方法接受上述和以下所述的四個參數:
- file:它是一個字符串,Buffer,URL或文件描述整數,表示必須在其中寫入文件的路徑。使用文件描述符將使其行為類似於fs.write()方法。
- data:它是將寫入文件的字符串,Buffer,TypedArray或DataView。
- options:它是一個字符串或對象,可用於指定將影響輸出的可選參數。它具有三個可選參數:
- encoding:它是一個字符串值,用於指定文件的編碼。默認值為“ utf8”。
- mode:它是一個整數值,指定文件模式。默認值為0o666。
- flag:它是一個字符串值,用於指定寫入文件時使用的標誌。默認值為“ w”。
- callback:執行該方法時將調用該函數。
- err:如果操作失敗,將引發此錯誤。
以下示例說明了Node.js中的fs.writeFile()方法:
範例1:
// Node.js program to demonstrate the
// fs.writeFile() method
// Import the filesystem module
const fs = require('fs');
let data = "This is a file containing a collection of books.";
fs.writeFile("books.txt", data, (err) => {
if (err)
console.log(err);
else {
console.log("File written successfully\n");
console.log("The written has the following contents:");
console.log(fs.readFileSync("books.txt", "utf8"));
}
});
輸出:
File written successfully The written has the following contents: This is a file containing a collection of books.
範例2:
// Node.js program to demonstrate the
// fs.writeFile() method
// Import the filesystem module
const fs = require('fs');
let data = "This is a file containing a collection of movies.";
fs.writeFile("movies.txt", data,
{
encoding:"utf8",
flag:"w",
mode:0o666
},
(err) => {
if (err)
console.log(err);
else {
console.log("File written successfully\n");
console.log("The written has the following contents:");
console.log(fs.readFileSync("movies.txt", "utf8"));
}
});
輸出:
File written successfully The written has the following contents: This is a file containing a collection of movies.
參考: https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback
相關用法
- Node.js GM drawCircle()用法及代碼示例
- Node.js GM drawBezier()用法及代碼示例
- Node.js GM drawPolyline()用法及代碼示例
- Node.js GM drawArc()用法及代碼示例
- Node.js GM drawEllipse()用法及代碼示例
- Node.js GM monochrome()用法及代碼示例
- Node.js GM equalize()用法及代碼示例
- Node.js GM enhance()用法及代碼示例
- Node.js GM drawPolygon()用法及代碼示例
- Node.js GM whitePoint()用法及代碼示例
注:本文由純淨天空篩選整理自sayantanm19大神的英文原創作品 Node.js | fs.writeFile() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。