编码
我在处理上传的节点 app.coffee 文件中有这个咖啡脚本代码:
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 "/"
在 JavaScript 转换中,它看起来像这样:
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("/");
});
});
});
Jade格式的表格:
form(action="", method="post", enctype="multipart/form-data")
input(type="file", name="displayImage")
input(type="submit", name="Upload")
来自控制台输出的 req.files
文件数据如下所示:
{ 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] } }
问题
我已经读过 JSON 文件的正确 mime 类型,application/json
但是正如您所看到的,它如上application/octet-stream
所示req.files
。这使我无法从类型键中检查类型。检查上传的文件是否是 Node JS 中的有效 JSON 文件的最佳方法是什么?
尝试/捕捉阅读?或者 Node 的某种 lint 插件?什么是实用的方法?