[英]How do I read a file in an async function without promises?
I'm trying to read/write to a file in an async function (example): 我正在尝试在异步函数中读取/写入文件(示例):
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));
}
But whenever I run it I always get the error: 但是每当我运行它时,我总是会得到错误:
(node:13480) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): TypeError: Cannot read property 'map' of null
I tried using bluebird by installing it using npm install bluebird
in my project directory and adding: 我尝试通过在项目目录中使用
npm install bluebird
并添加以下内容来尝试使用bluebird:
const Bluebird = require('bluebird');
const fs = Bluebird.promisifyAll(require('fs'));
to my index.js
(main) file, as well as adding: 到我的
index.js
(主)文件中,并添加:
const fs = require('fs');
to every file where I wan't to use fs. 到我不想使用fs的每个文件。
I still get the same error and can only narrow down the problem to fs through commenting out stuff. 我仍然遇到相同的错误,只能通过注释掉东西将问题缩小到fs。
Any help would be appreciated. 任何帮助,将不胜感激。
First of all: async
function
s return a promise. 首先:
async
function
返回一个Promise。 So by definition, you are already using a promise. 因此,根据定义,您已经在使用诺言。
Second, there is no fs.writeFileAsync
. 其次,没有
fs.writeFileAsync
。 You are looking for fs.writeFile
https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback 您正在寻找
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);
}
In the above: We used util.promisify to turn the nodejs callback style using functions to promises. 在以上内容中:我们使用util.promisify来使用功能将诺言转换为nodejs回调样式。 Inside an async function, you can use the await keyword to store the resolved contents of a promise to a const/let/var.
在异步函数内部,您可以使用await关键字将承诺的已解析内容存储到const / let / var。
Further reading material: https://ponyfoo.com/articles/understanding-javascript-async-await 进一步的阅读材料: 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.