【问题标题】:nodejs: Iterating through directory and capturing SHA256 value for each filenodejs:遍历目录并为每个文件捕获 SHA256 值
【发布时间】:2020-03-30 20:48:04
【问题描述】:

目标:遍历X目录下的所有文件,获取每个文件的SHA256值。

下面的代码似乎几乎可以工作;它捕获 ONE 文件的 SHA256 值,但在下一次迭代中失败。我做了一些谷歌搜索,但由于我对节点的了解有限,我无法找到答案。

推测:第一次迭代后;代码找不到完整路径了吗?

错误:[Error: ENOENT: no such file or directory, open 'example.txt'] { errno: -2, code: 'ENOENT', syscall: 'open', path: 'example.txt' }

example.txt 是我目录中的第二个文件,代码能够获取第一个文件的值。

const fs = require('fs').promises
const hasha = require('hasha');
const path = require('path')

async function getAllFiles(pathToFiles){
    let files = await fs.readdir(pathToFiles);
    for (const file of files) {
        const fullPath = path.join(pathToFiles, file)
        const hash = await hasha.fromFile(file.toString(), {algorithm: 'sha256'});
        console.log(hash);   

    }
}
getAllFiles('.').then(() => {
    console.log("all done");
}).catch(err => {
    console.log(err);
});

【问题讨论】:

    标签: javascript node.js loops iterator sha256


    【解决方案1】:

    想出了一个解决方案:获取每个文件的绝对路径并将该路径传递给 const hash 有效。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-12-29
      • 1970-01-01
      • 2021-01-16
      • 1970-01-01
      • 2011-01-31
      • 2015-12-30
      • 2019-01-16
      相关资源
      最近更新 更多