node.js 中 fs.writefile() 方法的寫入?yún)?shù)包括:文件路徑:要寫入的文件的絕對或相對路徑。數(shù)據(jù):要寫入文件的數(shù)據(jù)(字符串、buffer 或數(shù)據(jù)塊數(shù)組)。選項(可選):包含以下可選屬性:encoding:數(shù)據(jù)編碼(默認為 ‘utf8’)mode:文件權(quán)限模式(默認為 0o666)flag:打開文件時的標記(默認為 ‘w’)
Node.js 文件寫入?yún)?shù)
在 Node.js 中使用 fs.writeFile()
方法寫入文件時,可以傳遞以下參數(shù):
1. 文件路徑
指定要寫入的文件的路徑。可以是絕對路徑或相對于當前工作目錄的相對路徑。
2. 數(shù)據(jù)
要寫入文件的數(shù)據(jù)。可以是字符串、Buffer 或包含數(shù)據(jù)塊的數(shù)組。
3. 選項(可選)
一個包含可選配置的 JavaScript 對象。可以包括以下屬性:
encoding:數(shù)據(jù)編碼,默認為 ‘utf8’。
mode:文件權(quán)限模式,默認為 0o666。
flag:打開文件時的標記,默認為 ‘w’(覆蓋寫入)。
示例:
<code class="javascript">const fs = require('fs'); fs.writeFile('myFile.txt', 'Hello world!', (err) => { if (err) throw err; console.log('File written successfully.'); }); // 使用選項 fs.writeFile('myFile2.txt', 'Hello again!', { encoding: 'ascii' }, (err) => { if (err) throw err; console.log('File written successfully with ASCII encoding.'); });</code>
登錄后復(fù)制
詳細信息:
encoding:指定要寫入文件的數(shù)據(jù)的編碼。支持的編碼包括 ‘utf8’、’ascii’、’base64’ 等。
mode:設(shè)置文件的權(quán)限模式。該值是一個八進制數(shù),表示文件所有者、組和世界對文件的讀、寫和執(zhí)行權(quán)限。
flag:指定打開文件時的標記。其他支持的標記包括 ‘r’(讀取)、’a’(追加)、’w+’(讀寫覆蓋)等。