How to read the content of a directory

CodingHub
2 min readJun 11, 2021

Hi Friends, In the previous article, 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 article

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;
rimraf(`./public/uploads/${filename}`, function() {
console.log("remove folder if exists ");
fs.mkdir(`./public/uploads/${filename}`, function(err) {
if (err) {
console.log(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(`./public/uploads/${filename}`, options);
let dataBuffer = fs.readFileSync(`./public/uploads/${filename}`);
pdf(dataBuffer).then(function(data) {
for (var pageToConvertAsImage = 1; pageToConvertAsImage <= data.numpages; pageToConvertAsImage++) {
storeAsImage(pageToConvertAsImage).then((resolve) => {
return resolve;
});
}
});
const testFolder = `./public/uploads/${foldername}/`;
const tree = dirTree(testFolder);
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.

Originally published at https://www.codinghub.net.

--

--