How to read the content of a directory and return JSON object - node.js

How to read the content of a directory and return JSON object - node.js

Hi Friends, In previous Articles I have written the process about how to convert the PDF pages to PNG In this article I will tell you how to read the converted images and return those images as a REST API endpoint. So Lets Start.

If you didn't read my previous article Please go through it since this is the extension of that articles

How to convert PDF file pages to PNG images-node.js

We will create the Two endpoints

app.js file

var express = require("express");
var router = express.Router();
const { fromPath } = require("pdf2pic");
const pdf = require("pdf-page-counter");
const fs = require("fs");
var app = express();

app.get("/getfiles", (req, res, next) => {
    foldername = req.query.filename;
    const testFolder = `./public/uploads/${foldername}/`;
    const tree = dirTree(testFolder);
    res.send({ message: tree });

app.get("/pdfToPng", (req, res, next) => {
    const { filename } = req.query;
    //If folder exitst then remove
    rimraf(`./public/uploads/${filename}`, function () {
        console.log("remove folder if exists ");

        fs.mkdir(`./public/uploads/${filename}`, function (err) {
            if (err) {
            } else {
                console.log("New directory successfully created.");
                const options = {
                    quality: 100,
                    saveFilename: filename,
                    savePath: `./public/uploads/${filename}`,
                    format: "png",
                    width: 904,
                    height: 513,
                    page: 100,
                const storeAsImage = fromPath(

                let dataBuffer = fs.readFileSync(
                pdf(dataBuffer).then(function (data) {
                    for (
                        var pageToConvertAsImage = 1;
                        pageToConvertAsImage <= data.numpages;
                    ) {
                        storeAsImage(pageToConvertAsImage).then((resolve) => {
                            return resolve;

                const testFolder = `./public/uploads/${foldername}/`;
                const tree = dirTree(testFolder);
                //console.log("FILE DETAILS", tree);
                res.send({ message: tree });               

That's it. You will get the response with the complete list of items as a JSON object through calling the REST API. Thanks for reading the article.

Related Articles