How to Scan a File for Viruses & Malware in Node.js
There’s no such thing as too much file security. New types of malware are developed almost daily, and if we don’t adequately protect ourselves against both new & existing threats, we can easily fall victim to them.
Using the below Node.js code examples, we can take advantage of a free-to-use API that scans individual files for viruses and malware. This service combines signature-based scanning with heuristics and other cutting-edge predictive threat detection methods, making it possible to identify both established and unknown threat types lurking within compromised files. We can run a wide variety of files through this scan, too, including archive Office & PDF formats, HTML, and archive files among others.
We can structure our API call in a few quick steps using minimal code. First, let’s either install the SDK by running the below command:
npm install cloudmersive-virus-api-client --save
Or by adding the following snippet to our package.json:
"dependencies": {
"cloudmersive-virus-api-client": "^1.1.9"
}
Finally, let’s copy the below code examples into our file. To authorize our request, we’ll just need a free-tier API key from the Cloudmersive website — this will allow us to make up to 800 API calls per month with no additional commitments:
var CloudmersiveVirusApiClient = require('cloudmersive-virus-api-client');
var defaultClient = CloudmersiveVirusApiClient.ApiClient.instance;
// Configure API key authorization: Apikey
var Apikey = defaultClient.authentications['Apikey'];
Apikey.apiKey = 'YOUR API KEY';
var apiInstance = new CloudmersiveVirusApiClient.ScanApi();
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.scanFile(inputFile, callback);
Please note that each file is scanned in-memory, and all file data is released upon completion of the scan. This allows for a high-speed service where content security is a top priority.
Now we can quickly & easily scan individual files for threats!