nodejs:遍历目录并为每个文件捕获 SHA256 值
nodejs: Iterating through directory and capturing SHA256 value for each file
目标:遍历 X 目录中的所有文件并获取每个文件的 SHA256 值。
下面的代码似乎几乎可以工作;它捕获了一个文件的 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);
});
找到一个解决方案:获取每个文件的绝对路径并将该路径传递给 const hash。
目标:遍历 X 目录中的所有文件并获取每个文件的 SHA256 值。
下面的代码似乎几乎可以工作;它捕获了一个文件的 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);
});
找到一个解决方案:获取每个文件的绝对路径并将该路径传递给 const hash。