Ba5*_*14n 2 javascript node.js
我有一个函数,它为给定的路径生成校验和
function getHash(path) {
var fs = require('fs');
var crypto = require('crypto');
var fd = fs.createReadStream(path);
var hash = crypto.createHash('sha1');
hash.setEncoding('hex');
fd.on('end', function () {
hash.end();
// *** Here is my problem ***
console.log(hash.read());
});
fd.pipe(hash);
};
Run Code Online (Sandbox Code Playgroud)
我想调用calcNewHash函数,以便它返回哈希,问题是,我没有找到这个的异步版本,也许有人可以帮助.
只是添加一个return语句不起作用,因为该函数在一个Listener中
后来我想将校验和添加到一个对象,所以我可以将它作为参数提供给它,但这仍然不会改变它是异步的......
你基本上有2个解决方案:
function getHash(path) {
var Q = require('q');
var fs = require('fs');
var crypto = require('crypto');
var deferred = Q.defer();
var fd = fs.createReadStream(path);
var hash = crypto.createHash('sha1');
hash.setEncoding('hex');
fd.on('end', function () {
hash.end();
// *** Here is my problem ***
console.log(hash.read());
deferred.resolve(hash.read());
});
fd.pipe(hash);
return deferred.promise;
};
getHash('c:\\')
.then(function(result) {
// do something with the hash result
});
Run Code Online (Sandbox Code Playgroud)
function getHash(path, cb) {
var fs = require('fs');
var crypto = require('crypto');
var fd = fs.createReadStream(path);
var hash = crypto.createHash('sha1');
hash.setEncoding('hex');
fd.on('end', function () {
hash.end();
// *** Here is my problem ***
console.log(hash.read());
if (cb) {
cb(null, hash.read());
}
});
fd.pipe(hash);
};
getHash('C:\\', function (error, data) {
if (!error) {
// do something with data
}
});
Run Code Online (Sandbox Code Playgroud)
如果你没有在回调函数中进行深度嵌套,我会选择#2选项.
(注意:幕后承诺也使用回调,如果你有深度嵌套,它只是一个'更清洁'的解决方案)
我知道这很旧,但当沿着这些方向搜索某些内容时,它位于顶部结果中。因此,对于那些在这里寻找解决方案的人来说,这里是:(请注意,只有当您知道文件很小时,这才有效。否则,对于较大的文件,请参阅 Dieterg 提供的答案)
const fs = require('fs');
const crypto = require('crypto');
function fileHashSync(filePath){
var fileData;
try{ fileData = fs.readFileSync(filePath, 'utf8'); }
catch(err){
if(err.code === 'ENOENT') return console.error('File does not exist. Error: ', err);
return console.error('Error: ', err);
}
return crypto.createHash('sha1').update(fileData, 'utf8').digest('hex');
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1066 次 |
| 最近记录: |