-1

I'm trying to create a function with node.js that checks the hash of an online file to see if it's been changed. Every time I call my function it always returns undefined. I understand the problem has something to do with asynchronous functions, but I don't quite understand how they work.

const crypto = require("crypto")
const request = require("request") 

function checkHash(url, hash) {
    request.get(url, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            if (crypto.createHash('md5').update(body).digest("hex") !== hash) {
                return true;
            } else {
                return false;
            }
        }
    });
}
crypt1c
  • 3
  • 3
  • You don't return any value. Check for promises in JS. – ventaquil Mar 11 '18 at 17:44
  • You cannot return 'values' from an asynchronous functions. Instead you should call the 'callback' function with the required value or error. You must go through basic Javascript tutorials. – Nidhin David Mar 11 '18 at 17:45

1 Answers1

1

Being an async call you must provide a way to rescue back your returned value. A possible approach are using callbacks as below:

const crypto = require("crypto")
const request = require("request") 

function checkHash(url, hash, callback) {
    request.get(url, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            if (crypto.createHash('md5').update(body).digest("hex") !== hash) {
                return callback(null, true);
            } else {
                return callback(null, false);
            }
        }
        return callback(error);
    });
}

then call chechHash passing a function as argument:

checkHash(url, hash, function(err, response) {
    if(err) return console.log(err);
    //response is here
})
guijob
  • 4,413
  • 3
  • 20
  • 39