简体   繁体   中英

having issues implementing util promisify in node js

I have been trying to get an example of util.promisify working on node (v 14) and for the life of me I can't get any of the examples available on the inte.net working.

this for example is a very simple example from a website which should work, but i always get an error saying "await is only valid in async function":

const fs = require('fs');
const util = require('util');

// Convert `fs.readFile()` into a function that takes the
// same parameters but returns a promise.
const readFile = util.promisify(fs.readFile);

// You can now use `readFile()` with `await`!
const buf = await readFile('../../package.json'); <-- this is where I get the error

const obj = JSON.parse(buf.toString('utf8'));
obj.name; // 'masteringjs.io'

console.log(obj);

I have even tried simple examples which don't use util.promisify but i can't get a single async await example from the inte.net to work.

What makes this even weirder is that quokka.js can run the code fine with no errors, it's only when I run node test.js that I get this error.

Quokka result for the code above:

短尾矮袋鼠结果

Have I turned off a setting in node or something?? I'm really confused.

This is working for me

const fs = require('fs');
const util = require('util');

// Convert `fs.readFile()` into a function that takes the
// same parameters but returns a promise.
const readFile = util.promisify(fs.readFile);


const readFiles = async (path) =>{
    const buf = await readFile(path);
    const obj = JSON.parse(buf.toString('utf8'));
    // obj.name; // 'masteringjs.io'
    console.log(obj);
}
readFiles('./package.json').catch(err => {
    console.log(err)
})

One more way you can use is shown below Having async as self executing function without adding async keyword to actual function

 const readFile = util.promisify(fs.readFile);

// You can now use `readFile()` with `await`!
(async(path) => {
    const buf = await readFile(path);

    const obj = JSON.parse(buf.toString('utf8'));
    obj.name; // 'masteringjs.io'
    console.log(obj);
})('./package.json')

The code was correct (as it was not my code it was taken from a working example).

The issue was that node does not support top level async/await using CommonJS modules. Set "type" to "module" in package.json to use ES6 modules.

Once the above setting is used the code runs perfectly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM