How to Validate DOCX Files in Node.js
It’s usually impossible to tell if a DOCX file is real, corrupt or fake from a quick glance at the file extension.
Thankfully, using the below code, you can take advantage of a free API that validates DOCX files in-depth and identifies any errors or warnings (if any) are present within the document. It’ll also callout if the document is password protected.
You can install the SDK by either running the below command:
npm install cloudmersive-convert-api-client --save
Or by adding the below snippet to your package.json:
"dependencies": {
"cloudmersive-convert-api-client": "^2.6.3"
}
Now you can structure your request using the ready-to-run Node.js code examples below. To authorize your request, input a free-tier API key (these can be obtained by registering a free account on the Cloudmersive website):
var CloudmersiveConvertApiClient = require('cloudmersive-convert-api-client');
var defaultClient = CloudmersiveConvertApiClient.ApiClient.instance;
// Configure API key authorization: Apikey
var Apikey = defaultClient.authentications['Apikey'];
Apikey.apiKey = 'YOUR API KEY';
var apiInstance = new CloudmersiveConvertApiClient.ValidateDocumentApi();
var inputFile = Buffer.from(fs.readFileSync("C:\\temp\\inputfile").buffer); // File | Input file to perform the operation on.
var callback = function(error, data, response) {
if (error) {
console.error(error);
} else {
console.log('API called successfully. Returned data: ' + data);
}
};
apiInstance.validateDocumentDocxValidation(inputFile, callback);
You’ll receive a response object determining the validity of your document. Easy!