emvo
emvo

Reputation: 117

Why does my Node application keep sending data after every refresh?

I am using node.js and express.js to build a very simple application. I want to read the content of a directory and when I browse to localhost:3000/names, the application will print an array of the content to the web page except for the content that I choose not to. Here is my code:

const express = require('express');
const fs = require('fs');
const app = express();
const port = 3000;

let result = [];

app.get('/names', (req, res) => {
  const printNames = (err, file) => {
    file.forEach(e => {
      if (e !== 'john') {
        result.push(e);
      }
    });
    res.send(result);
  };

  fs.readdir('./home', printNames);
});

app.listen(port, () => {
  console.log('Listening on port 3000');
});

The application works the way that I wanted to, but there is a small bug. Every time I refresh the page, the application will add on the same content of the array to the existing array. My array keeps getting bigger with every refresh. I want the application to send the array to the page and will stay the same when I refresh. I do not have the slightest idea why my application is behaving this way. Can someone explain to me why it is behaving like this and what would be the right steps to fix this?

Upvotes: 2

Views: 374

Answers (2)

Kayvan Mazaheri
Kayvan Mazaheri

Reputation: 2597

It is because you've declared your result array in the global scope.
Your result array is getting bigger and bigger every time.

Simply move the declaration to your route and you should be fine.

This should work fine:

const express = require('express');
const fs = require('fs');
const app = express();
const port = 3000;

// let result = [];                      Remove this line

app.get('/names', (req, res) => {
  let result = [];                    // And add it here

  const printNames = (err, file) => {
    file.forEach(e => {
      if (e !== 'john') {
        result.push(e);
      }
    });
    res.send(result);
  };

  fs.readdir('./home', printNames);
});

app.listen(port, () => {
  console.log('Listening on port 3000');
});

Read more about scopes in JavaScript here:
https://www.w3schools.com/js/js_scope.asp

Upvotes: 5

posit labs
posit labs

Reputation: 9431

Every time you request to load the page /names, it is re-running the code in that handler. If you only want to run that script once, then move it outside of the handler, and only send the result.

let result = [];

const printNames = (err, file) => {
    file.forEach(e => {
        if (e !== 'john') {
        result.push(e);
        }
    });
};

fs.readdir('./home', printNames);

app.get('/names', (req, res) => {
    res.send(result)
});

Upvotes: 1

Related Questions