简体   繁体   中英

Node.js confusing output from each loop

I'm wondering if someone can help me understand the following behaviour. If I have an app.js file on a node.js server such as below:

var http = require('http');
var _ = require('underscore');

http.createServer(function(request, response) {
var x = '';
    _.each([1, 2, 3], function(num){
    x +=" underscore.js says " + num;
});
    response.writeHead(200, {
        'Content-Type': 'text/html'
    })

    response.end(x);

      }).listen(3000, null);

Then everytime I request the page, I see the text "underscore.js say x" 3 times. I expect this as there are 3 numbers in the loop and x is reset on every request. However, if I have the following (x moved outside of callback for createServer):

var http = require('http');
var _ = require('underscore');
var x = ''; // Note x is moved outside the createserver callback
http.createServer(function(request, response) {

    _.each([1, 2, 3], function(num){
    x +=" underscore.js says " + num;
});
    response.writeHead(200, {
        'Content-Type': 'text/html'
    })

    response.end(x);

      }).listen(3000, null);

The first loads produces 3 results (as expected), but subsequent requests always append the loop twice (so 6 "underscore.js says x" lines. I can understand it's appending everytime to the same variable, but then I would expect it to to print out the results by multiples of 3 each time, so first call prints 3 lines total, second prints 6, 3rd prints 9 etc.

I'm quite new to node.js so would appreciate if someone could explain this behaviour or how this loop is working in a way I wouldn't expect.

thanks

This is probably a disappointing answer, but still.

Your browser will be making a HTTP request to /favicon.ico , which will be hitting your script and adding an additional 3 lines to your x variable for each request.

  1. You refresh your page and see 3 lines.
  2. Your browser requests /favicon.ico , and 3 additional lines are added
  3. You refresh the page, and see 6 lines + the 3 additional.
  4. Your browser requests /favicon.ico , and 3 additional lines are added

... etc.

You'll be able to fix this by checking the request.url parameter for ending in favicon.ico ;

if (/\/favicon.ico$/.test(request.url)) {
    // don't incremement
}

... or you can do it more funk-ily with the url() module;

if (require('url').parse(request.url).pathname === '/favicon.ico') {
    // don't incremement.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM