ac0437
ac0437

Reputation: 37

Node zlib.gzip returns undefined

I'm running this code in Node and for some reason when I result result it give undefined but when I console log it result is not undefined and I am really confused as to why:

const zlib = require('zlib');

function gzip(data) {
  zlib.gzip(data, (err, result) => {
    if (err) return err;
    console.log(result, data);
    return result;
  });
}

console.log(gzip('hello'));

console.log results

Info: Start process (8:31:38 PM)
undefined
Results: <Buffer 1f 8b 08 00 00 00 00 00 00 0a cb 48 cd c9 c9 07 00 86 a6 10 36 05 00 00 00> Data: hello
Info: End process (8:31:38 PM)

Upvotes: 0

Views: 1076

Answers (1)

Justin Moser
Justin Moser

Reputation: 2005

undefined is first logged because your function named gzip (function gzip(data) { ... }) does not return anything.

In attempt to help with the confusion, I'm betting the return statements in your callback function ((err, result) => { ... }) are not behaving as expected. The return statements in your callback function are not returning the value to you in a way that you could log. I recommend reading the node.js guide on callback functions to learn how they are used with asynchronous functions like zlib.gzip().

You might want to checkout the synchronous version, zlib.gzipSync(), as it may behave closer to your expectations right now. I also recommend reading the node.js guide Overview of Blocking vs Non-Blocking to learn about the differences between these kinds of synchronous and asynchronous functions in general.

Upvotes: 2

Related Questions