【问题标题】:How to add a callback in this function for gzip如何在此函数中为 gzip 添加回调
【发布时间】:2015-09-19 17:49:36
【问题描述】:

这是我的代码:

/*jshint globalstrict: true*/
var zlib = require('zlib');
var http = require('http');

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/html', 'Content-Encoding': 'gzip'});

    var text = "Hey this works!";
    zlib.gzip(text, function (_, result) {
        res.end(result);
    });
}).listen(8081);

我想在上面的代码中添加一个回调来遵循 node.js 的异步概念。我怎么做?另外,我对 node.js 很陌生

【问题讨论】:

  • 您已经添加了回调。实际问题是什么?此外,你真的不应该忽略回调的 err 参数(如果设置了 err,你至少应该发回 500 或类似的 HTTP 状态代码)。
  • 我在哪里添加了回调
  • 你的回调是包含res.end(result);的函数。

标签: javascript node.js callback gzip zlib


【解决方案1】:
 var callback = function (err, result) {
    // gzip has finished, do any thing you want here,
    // also add if about the 'err' as mscdex said.
    res.end(result);
 }
 zlib.gzip(text, callback);

回调是一个函数,你已经添加了。

【讨论】:

    猜你喜欢
    • 2023-03-18
    • 2023-03-07
    • 1970-01-01
    • 2013-12-18
    • 1970-01-01
    • 1970-01-01
    • 2020-05-03
    • 2017-05-21
    • 2010-11-01
    相关资源
    最近更新 更多