所以,代码有效,但缩进级别太疯狂了......节点中的所有回调,我应该如何编码?
"use strict";
var crypto = require('crypto'),
fs = require('fs'),
mmm = require('mmmagic'),
Magic = require('mmmagic').Magic,
path = require('path');
console.log('Init controller: ' + path.basename(__filename));
exports.help = function () {
var help;
help = "POST http://server/images\n";
help += " Upload image for storage.\n";
help += " <image> - The image file to upload\n";
help += " <title> - The title of the image, no more than 50 characters\n";
help += " <desc> - The description of the image, no more than 1024 characters\n";
return help;
}
exports.post = function (req, res) {
var image = req.files.image;
if (typeof(image) == 'undefined') {
res.status(400).send("{error:'Upload error'}");
return;
}
var magic = new Magic(mmm.MAGIC_MIME_TYPE);
magic.detectFile(image.path, function(err, result) {
if (err) {
res.status(400).send("{error:'Upload mime error'}");
} else {
var mime = result.toLowerCase().split('/');
if (mime[0] != 'image') {
res.status(400).send("{error:'Upload not an image', mime: '" + result + "'}");
} else {
// Read the image file
fs.readFile(image.path, function (err, data) {
if (err) {
res.status(400).send("{error:'Upload read error'}");
} else {
var hash = crypto.createHash('md5').update(data).digest("hex");
req.app.models.image.count({'hash': hash}, function (err, count) {
if (err) {
res.status(400).send("{error:'ORM Error: '" + JSON.stringify(err) + "'}");
} else {
if (count > 0) {
res.status(400).send("{error:'Image already exists'}");
} else {
var hash = crypto.createHash('md5').update(data).digest("hex");
var newPath = path.join(req.app.tempDir, hash);
fs.writeFile(newPath, data, function (err) {
if (err) {
res.status(400).send("{error:'Upload write error'}");
} else {
// Save the image
req.app.models.image.create([{
'hash' : hash,
'mime' : mime,
title : '',
description : ''
}], function(err, images) {
if (err) {
fs.unlink(newPath);
res.status(400).send("{error:'" + err.message + "'}");
} else {
res.status(200).send("{id:'" + images[0].id + "}");
}
});
}
});
}
}
});
}
});
}
}
});
}