How to read file with async/await properly?
我无法弄清楚
1 2 3 4 5 6 7 8 9 | function loadMonoCounter() { fs.readFileSync("monolitic.txt","binary", async function(err, data) { return await new Buffer( data); }); } module.exports.read = function() { console.log(loadMonoCounter()); }; |
我知道我可以使用
目标:调用
每次调用
无论我做什么,我都会在控制台中收到错误或
由于Node v11.0.0 fs promises可以直接在没有
1 2 3 4 5 | const fs = require('fs').promises; async function loadMonoCounter() { const data = await fs.readFile("monolitic.txt","binary"); return new Buffer(data); } |
要使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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); }) |
注意,
这是@Joel答案的TypeScript版本。在节点11.0之后可用:
1 2 3 4 5 6 | import { promises as fs } from 'fs'; async function loadMonoCounter() { const data = await fs.readFile('monolitic.txt', 'binary'); return Buffer.from(data); } |
您可以像这样用promise轻松包装readFile命令:
1 2 3 4 5 6 7 8 9 10 | async function readFile(path) { return new Promise((resolve, reject) => { fs.readFile(path, 'utf8', function (err, data) { if (err) { reject(err); } resolve(data); }); }); } |
然后使用:
1 | await readFile("path/to/file"); |
您可以使用从Node v11.0.0开始本地可用的
1 2 3 4 5 6 7 8 9 10 11 | import fs from 'fs'; const readFile = async filePath => { try { const data = await fs.promises.readFile(filePath, 'utf8') return data } catch(err) { console.log(err) } } |
有一个
为了使其简洁并保留
1 2 3 4 5 6 7 | const fs = require('fs'); const fsPromises = fs.promises; async function loadMonoCounter() { const data = await fsPromises.readFile('monolitic.txt', 'binary'); return new Buffer(data); } |
分别导入
1 2 3 4 | // 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')); |