BrTkCa
BrTkCa

Reputation: 4783

Check if file is corrupted with node.js

There are some ways to check file is corrupted with node.js?

I tried many File System methods, like fs.readFile, fs.open and fs.access but all of them return ok status, and I'm sure my file is corrupted in my tests.

To be more clear, my objective is to check if PDF is readable (not only check if can be generated) and if can be opened. I damaged the file online to test.

Upvotes: 5

Views: 7186

Answers (2)

Dinesh Reddy
Dinesh Reddy

Reputation: 11

Actually, u can use another npm to check file corruption of pdf.

npm i pdf-parse
const pdfParser = require('pdf-parse')
try {
  let bufferData = fs.readFileSync(`${target}/corrupted.pdf`)
  pdfParser(bufferData).then((data) => {
    // do something with data
  }).catch((error) => {
    console.log(error.message)
  })
} catch (error) {
  console.log(error)
}

For corrupted file the error might seem like:
Warning: Indexing all PDF objects
Invalid PDF structure

Upvotes: 1

ookadoo
ookadoo

Reputation: 147

You could try to parse it with a tool like this and confirm if it was successful.

To expand on that a little, here's some example code lifted from the link:

let fs = require('fs'),
    PDFParser = require("pdf2json");

let pdfParser = new PDFParser();

pdfParser.on("pdfParser_dataError", errData => console.error(errData.parserError) );
pdfParser.on("pdfParser_dataReady", pdfData => {
    fs.writeFile("./pdf2json/test/F1040EZ.json", JSON.stringify(pdfData));
});

pdfParser.loadPDF("./pdf2json/test/pdf/fd/form/F1040EZ.pdf");

Upvotes: 4

Related Questions