fs.readdir ignore directories

后端 未结 2 1054
温柔的废话
温柔的废话 2021-02-08 00:20

I would like to scan the folder, but ignore all the folders/directories that are included in it. All I have in the (C:/folder/) are .txt files and other folders, I just want to

2条回答
  •  臣服心动
    2021-02-08 00:31

    Please See diraria's answer as it is more complete: my answer only works if ALL filenames contain a '.txt' extension.

    why not just filter out files that end in ".txt"?

    var fs = require("fs")
    fs.readdirSync("./").filter(function(file) {
        if(file.indexOf(".txt")>-1)console.log(file)
    })
    

    I should have added previously that to get an array of these files you need to return them to an array as shown below.

    var fs = require("fs")
    let text_file_array = fs.readdirSync("./").filter(function(file) {
        if(file.indexOf(".txt")>-1) return file;
    })
    

提交回复
热议问题