1

I have a simple Node.js server in which I'm trying to use a Node.js package called image-similarity, according to its doc it is used like this:

let  imageSimilarity  = require ('image-similarity') ; 
imageSimilarity('./image/1.jpg', './image/2.jpg').then ( res =>  { 
    console.log(res) ; // The  similarity is 0.8162515507509954 
} ) ;

It works fine like that but I'm trying to use it inside an HTTP Node.js server, like this:

var http = require('http');
var imageSimilarity = require('image-similarity');

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

    var result = "";

    imageSimilarity('./images/1.png', './images/2.png').then(res => {
        result = res;
    });

    res.end(result);
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

I just need to add the result to the response, but I found that I cannot access the res variable from inside the then function, and I cannot simply assign the result to a variable like in the previous example since that block is executed asynchronously it will simply be empty when I try to use it outside.

1
  • use then() for result as far as imageSimilarity is async Commented Apr 14, 2020 at 7:46

1 Answer 1

2

You are running into problems with it being async, you need to call res.end(result) from within your then()

var http = require('http');
var imageSimilarity = require('image-similarity');

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

    imageSimilarity('./images/1.png', './images/2.png').then(result => {
        res.end(result);
    });


}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

also I note I renamed the then's argument to result to avoid naming clashes with the outer res

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.