[英]To count files present in a directory with specific extension in node.js
In a given task,I need to count file with extensions such as '.js','.txt' and other remaining extensions by using promise.在给定的任务中,我需要使用 promise 计算扩展名为“.js”、“.txt”和其他剩余扩展名的文件。
const fs = require("fs");
const path = require("path");
function fun(pathTodirectory) {
return new Promise(resolve => {
fs.readdir(pathTodirectory, (error, files) => {
if (error) {
reject("Error occured");
}
else {
var obj = {
countJs: function () {
var count = 0;
for (var i = 0; i < files.length; i++) {
if (path.extname(files[i]) === ".js") {
count++;
}
}
return count;
},
countTxt: function () {
var count = 0;
for (var i = 0; i < files.length; i++) {
if (path.extname(files[i]) === ".txt") {
count++;
}
}
return count;
},
count: function () {
var count = 0;
for (var i = 0; i < files.length; i++) {
if (path.extname(files[i]) !== ".js" && path.extname(files[i] !== ".txt")) {
count++;
}
}
return count;
},
files: files //will print list of all files in form of array.
}
resolve(obj);
}
});
});
}
//then part for promise.
This is my code so far,I'm getting problem in my code.The count
part in not working and giving assertion error in console.到目前为止,这是我的代码,我的代码出现问题。 count
部分不工作并在控制台中给出断言错误。 I need to resolve in form of object only.我只需要以对象的形式解决。 How do i effectively do this?我如何有效地做到这一点?
You never define path
anywhere in the function.你永远不会在函数的任何地方定义path
。 Unless you're defining it somewhere else that'll cause your error.除非你在其他地方定义它会导致你的错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.