请帮忙看一下这段http访问网络的代码有没有明显的逻辑错误,谢谢
发布于 2年前 作者 mz121star 746 次浏览

写了一段代码,请各位兄弟姐妹大叔大爷看一下,有没有逻辑错误?使用时候会不会出现什么问题?谢谢~代码如下

var http = require(“http”); (function () { var mhttp; mhttp = { get:function (url) { var scuessCallbacks = [], errorCallbacks = [], responseHTML; var deferred = { done:function (callback) { if (typeof callback === ‘function’) scuessCallbacks.push(callback); return this; }, fail:function (callback) { if (typeof callback === ‘function’) errorCallbacks.push(callback); return this; } } http.get(url, function (res) { res.on('data’,function (d) { responseHTML = responseHTML + d; }).on('end’,function () { for (i = 0, n = scuessCallbacks.length; i < n; i++) { scuessCallbacksi; } }).on('error’, function (e) { for (i = 0, n = errorCallbacks.length; i < n; i++) { errorCallbacksi; } }); }); return deferred; } } module.exports = mhttp; })(module);

调用如下

  mhttp.get(file_url).done(function (data) {
        var mfile = fs.createWriteStream(DOWNLOAD_DIR + file_name);
        mfile.write(data);
    });
2 回复
var http = require("http");
(function () {
    var mhttp;
    mhttp = {
    get:function (url) {
        var scuessCallbacks = [],
            errorCallbacks = [],
            responseHTML;
        var deferred = {
            done:function (callback) {
                if (typeof callback === 'function') scuessCallbacks.push(callback);
                return this;
            },
            fail:function (callback) {
                if (typeof callback === 'function') errorCallbacks.push(callback);
                return this;
            }
        }
        http.get(url, function (res) {
            res.on('data',function (d) {
                responseHTML = responseHTML + d;
            }).on('end',function () {
                    for (i = 0, n = scuessCallbacks.length; i < n; i++) {
                        scuessCallbacks[i](responseHTML);
                    }
                }).on('error', function (e) {
                    for (i = 0, n = errorCallbacks.length; i < n; i++) {
                        errorCallbacks[i](e);
                    }
                });
        });
        return deferred;
    }
}
module.exports = mhttp;
})(module);
回到顶部