How to test if the uploaded file is a json file in Node JS?
file-type, file-upload, javascript, json, node.js
Solution
You can try to parse the JSON on server side:
function validateJSON(body) {
try {
var data = JSON.parse(body);
// if came to here, then valid
return data;
} catch(e) {
// failed to parse
return null;
}
}
And then you can use it like that:
var data = validateJSON('some potential json data');
if (data) {
// valid!
}
Problem
The Code I have this coffee-script code on my node app.coffee file that handles the upload: ``` app.post "/import", (req, res) -> console.log req.files fs.readFile req.files.displayImage.path, (err, data) -> newPath = __dirname + "/uploads/" + req.files.displayImage.name fs.writeFile newPath, data, (err) -> throw err if err res.redirect "/" ``` In JavaScript conversion it appears like this: ``` app.post("/import", function(req, res) { console.log(req.files); return fs.readFile(req.files.displayImage.path, function(err, data) { var newPath; newPath = __dirname + "/uploads/" + req.files.displayImage.name; return fs.writeFile(newPath, data, function(err) { if (err) { throw err; } return res.redirect("/"); }); }); }); ``` The form in Jade format: ``` form(action="", method="post", enctype="multipart/form-data") input(type="file", name="displayImage") input(type="submit", name="Upload") ``` req.files from Console Output The file data looks like this: ``` { displayImage: { domain: null, _events: {}, _maxListeners: 10, size: 1148, path: '/tmp/21096ac17833fa5e096f9e5c58a5ba08', name: 'package.json', type: 'application/octet-stream', hash: null, lastModifiedDate: Wed Jul 17 2013 22:04:58 GMT-0400 (EDT), _writeStream: { _writableState: [Object], writable: true, domain: null, _events: [Object], _maxListeners: 10, path: '/tmp/21096ac17833fa5e096f9e5c58a5ba08', fd: null, flags: 'w', mode: 438, start: undefined, pos: undefined, bytesWritten: 1148, closed: true, open: [Function], _write: [Function], destroy: [Function], close: [Function], destroySoon: [Function], pipe: [Function], write: [Function], end: [Function], setMaxListeners: [Function], emit: [Function], addListener: [Function], on: [Function], once: [Function], removeListener: [Function], removeAllListeners: [Function], listeners: [Function] }, open: [Function], toJSON: [Function], write: [Function], end: [Function], setMaxListeners: [Function], emit: [Function], addListener: [Function], on: [Function], once: [Function], removeListener: [Function], removeAllListeners: [Function], listeners: [Function] } } ``` The Question I've read that the correct mime type for a JSON file is `application/json` however as you can see it shows up as `application/octet-stream` in `req.files` above. This prevents me from checking the type from the type key. What would be the best way to check if the uploaded file is a valid JSON file in Node JS? A try/catch reading? Or some sort of lint plugin for Node? What is a practical approach for this?