我正在尝试制作一个函数,该函数可以读取文件并返回哈希值,并且可以同步使用。
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关键字...
如果await运算符后面的表达式的值不是Promise,则将其转换为解析的Promise。
readStream.on
不会返回承诺,因此您的代码将无法按预期工作。
而不是使用await
,readStream.on
在aPromise
和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);
})();
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句