node.js - node.js 的新手,我不确定我这样做是否正确

标签 node.js

所以,代码可以工作,但是缩进级别太疯狂了...有了 Node 中的所有回调,我应该如何编码?

"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 + "}");
                                                }
                                            });
                                        }
                                    });
                                }
                            }
                        });
                    }
                });
            }
        }
    });
}

最佳答案

http://callbackhell.com/有一个适应异步编程的指南。

评论的一些跟进:

  • 有项目如Node FibersIced CoffeeScript如果使异步代码看起来像自上而下的同步代码对您有吸引力,并且被这种错觉误导不会让您非常紧张。但是,我强烈建议使用常规 javascript 和带有回调(不是 promise )的异步编程,直到灯泡亮起,然后再探索您并不真正理解的“问题”的解决方案。
  • 异步代码是操作系统完成 I/O 时执行的一堆代码。这就是为什么它不是自上而下阅读的原因——因为它不是自上而下执行的。它会在 IO 完成时执行,这就是它按其执行方式缩放的原因。
  • 不要被初学者的代码片段误导。在决定异步代码不可读之前,先看看像 TJ Holowaychuk 这样的大师的代码。回调 hell 是初学者现象。它非常普遍。几乎每个人都将它作为一个阶段经历,但超越它并不是特别困难,特别是考虑到掌握多线程锁定和信号量及其调试的替代方案。可读性好的异步代码通常都是直接设计得更好的代码。但是,是的,它缺乏同步代码的自上而下的有序性,这意味着在源代码中有更多的跳跃。

关于node.js - node.js 的新手,我不确定我这样做是否正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18691826/

相关文章:

node.js - Bluebird - 如何以 block 的形式循环遍历数组,等待 block 响应

javascript - MongoDB 通过 findOne 连接集合

node.js - Nginx 重定向到 Node.js 后端

node.js - 环回模型验证失败(异步行为)

javascript - 使用 Service Worker 时离线重写 URL

node.js - 管道到标准输出和可写流

javascript - Node.js 和 Jquery 传递变量

node.js - 我无法在ubuntu16.04上运行nodejs

node.js - 如何验证服务器上的 FCM 注册 token ?

node.js - 通过exec或spawn从node.js启动couchdb