[英]How do I read a file in an async function without promises?
我正在嘗試在異步函數中讀取/寫入文件(示例):
async readWrite() {
// Create a variable representing the path to a .txt
const file = 'file.txt';
// Write "test" to the file
fs.writeFileAsync(file, 'test');
// Log the contents to console
console.log(fs.readFileAsync(file));
}
但是每當我運行它時,我總是會得到錯誤:
(node:13480) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): TypeError: Cannot read property 'map' of null
我嘗試通過在項目目錄中使用npm install bluebird
並添加以下內容來嘗試使用bluebird:
const Bluebird = require('bluebird');
const fs = Bluebird.promisifyAll(require('fs'));
到我的index.js
(主)文件中,並添加:
const fs = require('fs');
到我不想使用fs的每個文件。
我仍然遇到相同的錯誤,只能通過注釋掉東西將問題縮小到fs。
任何幫助,將不勝感激。
首先: async
function
返回一個Promise。 因此,根據定義,您已經在使用諾言。
其次,沒有fs.writeFileAsync
。 您正在尋找fs.writeFile
https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback
const fs = require('fs');
const util = require('util');
// Promisify the fs.writeFile and fs.readFile
const write = util.promisify(fs.writeFile);
const read = util.promisify(fs.readFile);
async readWrite() {
// Create a variable representing the path to a .txt
const file = 'file.txt';
// Write "test" to the file
await write(file, 'test');
// Log the contents to console
const contents = await read(file, 'utf8');
console.log(contents);
}
在以上內容中:我們使用util.promisify來使用功能將諾言轉換為nodejs回調樣式。 在異步函數內部,您可以使用await關鍵字將承諾的已解析內容存儲到const / let / var。
進一步的閱讀材料: https : //ponyfoo.com/articles/understanding-javascript-async-await
const fs = require('fs');
async readWrite() {
// Create a variable representing the path to a .txt
const file = 'file.txt';
// Write "test" to the file
fs.writeFile(file, 'test', err => {
if (!err) fs.readFile(file, 'utf8', (err, contents)=> {
console.log(contents);
})
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.