hash.js
var crypto = require('crypto'),
fs = require('fs')
var algorithm = 'sha256',
shasum = crypto.createHash(algorithm)
// Updating shasum with file content
var filename = __dirname + "/hufs.png",
s = fs.ReadStream(filename)
s.on('data', function(data) {
shasum.update(data)
})
// making digest
s.on('end', function() {
var hash = shasum.digest('hex') // this var
console.log(hash + ' ' + filename)
})
我有这个代码,然后我想从函数
中调用var'hash'我不知道该怎么做,我想要修复代码
我需要你的帮助
答案 0 :(得分:0)
要获取哈希的结果,必须在触发“结束”事件后获取值,并且如果您执行相同的代码
var hash;
s.on('end', function() {
hash = shasum.digest('hex') // this var
console.log(hash + ' ' + filename)
})
console.log(hash);
你的哈希将是“未定义的”,因为在事件触发后你的“console.log(hash)”将被执行
var crypto = require('crypto'),
fs = require('fs')
var algorithm = 'sha256',
shasum = crypto.createHash(algorithm)
// Updating shasum with file content
var filename = __dirname + "/3.png",
s = fs.ReadStream(filename)
s.on('data', function(data) {
shasum.update(data)
})
// making digest
var hash;
s.on('end', function() {
hash = shasum.digest('hex') // this var
console.log(hash + ' ' + filename)
})
// Here I simulate some code that will be executed after the "end" event was trigger
setTimeout(function(){
console.log(hash);
},5000);