我正在尝试创建一个读取文件并返回哈希值的函数,并且可以同步使用。
export async function hash_file(key) {
// open file stream
const fstream = fs.createReadStream("./test/hmac.js");
const hash = crypto.createHash("sha512", key);
hash.setEncoding("hex");
// once the stream is done, we read the values
let res = await readStream.on("end", function() {
hash.end();
// print result
const res = hash.read();
return res;
});
// pipe file to hash generator
readStream.pipe(hash);
return res;
}
似乎我正在放置await关键字错误...
答案 0 :(得分:1)
如果await运算符后面的表达式的值不是a 承诺,它已转换为已解决的承诺。
readStream.on
不会返回承诺,因此您的代码将无法按预期运行。
而不是使用await
,在readStream.on
和Promise
结束时将resolve
包裹起来。
function hash_file(key) {
// open file stream
const readStream = fs.createReadStream("./foo.js");
const hash = crypto.createHash("sha512", key);
hash.setEncoding("hex");
// once the stream is done, we read the values
return new Promise((resolve, reject) => {
readStream.on("end", () => {
hash.end();
// print result
resolve(hash.read());
});
readStream.on("error", reject);
// pipe file to hash generator
readStream.pipe(hash);
});
}
我正在尝试创建一个读取文件并返回哈希的函数 可以同步使用的
永远不会发生这种情况。您不能使异步代码同步。您可以使用async/await
使其看起来像是同步的,但它始终是异步的。
(async() => {
const hash = await hash_file('my-key'); // This is async.
console.log(hash);
})();