Nasuh Nasuh - 1 month ago 6
Node.js Question

Adding paths to file names that scanned with nodejs

I have this route in my app. Its scanning file names in some directories according to url parameter. Currently my JSON looks like;

[{"chapter":"642","paths":["00.png","01.png","02.png","03.png","04.png","05.png".....


Route:

app.get('/api/oku/:name', function (req, res) {
var files = fs.readdirSync('./public/manga/' + req.params.name);
var files = files.map(function(item){
var subfolders = fs.readdirSync('./public/manga/' + req.params.name + '/' + item);
return {
chapter: item,
paths: subfolders
}
})
res.json(files);
})


Simply I want to add paths to every image. Path that I want to add is;

"manga/" + req.params.name + "/" + item + "/"


So simply it will be looks like
manga/Naruto/542/00.png

Answer

Try this:

    app.get('/api/oku/:name', function (req, res) {
    var files = fs.readdirSync('./public/manga/' + req.params.name).map(function(item){
        var subfolders = fs.readdirSync('./public/manga/' + req.params.name + '/' + item);
        return {
            chapter: item,
            paths: subfolders.map(function (i) {
                return "manga/" + req.params.name + "/" + i + "/";
            }
        }
    })
    res.json(files);
})

Also, don't declare the files variable twice.