如何正确使用 async/await 读取文件?

问题描述 投票:0回答:13

我不知道

async
/
await
是如何工作的。我稍微理解了它,但我无法使它工作。

function loadMonoCounter() {
    fs.readFileSync("monolitic.txt", "binary", async function(err, data) {
       return await new Buffer( data);
  });
}

module.exports.read = function() {
  console.log(loadMonoCounter());
};

我知道,我可以使用

readFileSync
,但如果我这样做,我知道我永远不会理解
async
/
await
,我只会埋葬这个问题。

目标:调用

loadMonoCounter()
并返回文件内容。

每次调用

incrementMonoCounter()
(每次页面加载)时,该文件都会递增。该文件包含二进制缓冲区转储并存储在 SSD 上。

无论我做什么,我都会在控制台中收到错误或

undefined

node.js asynchronous readfile
13个回答
471
投票

自 Node v11.0.0 起,fs Promise 原生可用,无需

promisify
:

const fs = require('fs').promises;
async function loadMonoCounter() {
    const data = await fs.readFile("monolitic.txt", "binary");
    return Buffer.from(data);
}

233
投票

要使用

await
/
async
,您需要返回 Promise 的方法。如果没有像
promisify
:

这样的包装器,核心 API 函数就无法做到这一点
const fs = require('fs');
const util = require('util');

// Convert fs.readFile into Promise version of same    
const readFile = util.promisify(fs.readFile);

function getStuff() {
  return readFile('test');
}

// Can't use `await` outside of an async function so you need to chain
// with then()
getStuff().then(data => {
  console.log(data);
})

请注意,

readFileSync
不接受回调,它返回数据或引发异常。您没有获得所需的值,因为您提供的函数被忽略,并且您没有捕获实际的返回值。


65
投票

这是 @Joel 答案的 TypeScript 版本。 Node 11.0之后可以使用:

import { promises as fs } from 'fs';

async function loadMonoCounter() {
    const data = await fs.readFile('monolitic.txt', 'binary');
    return Buffer.from(data);
}

48
投票

您可以使用 Node v11.0.0 以来原生可用的

fs.promises

import fs from 'fs'; const readFile = async filePath => { try { const data = await fs.promises.readFile(filePath, 'utf8') return data } catch(err) { console.log(err) } }
    

34
投票
您可以轻松地用 Promise 包装 readFile 命令,如下所示:

async function readFile(path) { return new Promise((resolve, reject) => { fs.readFile(path, 'utf8', function (err, data) { if (err) { reject(err); } resolve(data); }); }); }

然后使用:

await readFile("path/to/file");
    

27
投票
从节点 v14.0.0 开始

const {readFile} = require('fs/promises'); const myFunction = async()=>{ const result = await readFile('monolitic.txt','binary') console.log(result) } myFunction()
    

15
投票
为了保持简洁并保留

fs

的所有功能:

const fs = require('fs'); const fsPromises = fs.promises; async function loadMonoCounter() { const data = await fsPromises.readFile('monolitic.txt', 'binary'); return Buffer.from(data); }
单独导入 

fs

fs.promises
 将允许访问整个 
fs
 API,同时保持其可读性......这样就可以轻松完成下一个示例之类的事情。

// the 'next example' fsPromises.access('monolitic.txt', fs.constants.R_OK | fs.constants.W_OK) .then(() => console.log('can access')) .catch(() => console.error('cannot access'));
    

5
投票
有一个

fs.readFileSync( path, options )

方法,它是同步的。


2
投票
const fs = require("fs"); const util = require("util"); const readFile = util.promisify(fs.readFile); const getContent = async () => { let my_content; try { const { toJSON } = await readFile("credentials.json"); my_content = toJSON(); console.log(my_content); } catch (e) { console.log("Error loading client secret file:", e); } };
    

2
投票
我使用

Promise

读取文件。对我来说这是正确的:

const fs = require('fs') //function which return Promise const read = (path, type) => new Promise((resolve, reject) => { fs.readFile(path, type, (err, file) => { if (err) reject(err) resolve(file) }) }) //example how call this function read('file.txt', 'utf8') .then((file) => console.log('your file is '+file)) .catch((err) => console.log('error reading file '+err)) //another example how call function inside async async function func() { let file = await read('file.txt', 'utf8') console.log('your file is '+file) }
    

0
投票
您可以在下面找到我的方法: 首先,我需要 fs 作为 fsBase,然后我将“promises”放入 fs 变量中。

const fsBase = require('fs'); const fs = fsBase.promises const fn = async () => { const data = await fs.readFile('example.txt', 'utf8'); console.log(data); }; fn();
    

0
投票
这会根据文件的内容生成一个字符串,您不需要使用 Promise 来实现此功能

const fs = require('fs'); const data = fs.readFileSync("./path/to/file.json", "binary");
    

-2
投票
看这个例子

https://www.geeksforgeeks.org/node-js-fs-readfile-method/

// Include fs module var fs = require('fs'); // Use fs.readFile() method to read the file fs.readFile('demo.txt', (err, data) => { console.log(data); })

© www.soinside.com 2019 - 2024. All rights reserved.