mohamed atef
mohamed atef

Reputation: 29

Writing data to JSON file using nodeJS takes too long

i am creating a function that Count the clicks of elements , and put them in JSON file

const fs = require('fs');
const file = fs.readFileSync('public/js/count.json');
const Words = JSON.parse(file);

const express = require('express');
const app = express();
app.listen(process.env.PORT || 3000, () => console.log('we are listeining'));
app.use(express.static('public'));
app.use(express.json({ limit : '1mb' })); 

app.get('/add/:word', addWord);

function addWord(request, response) {
  var data = request.params;
  var word = data.word;
  var reply;
  var found = false;
  for (i = 0; i < Words.length; i++){
    if (Words[i].type == word){
      Words[i].count++;
      found = true;
      break;
    }
  }

if (!found) {
  Words.push({"type": word , "count": 1});
}

  var x = JSON.stringify(Words, null, 2);
  fs.writeFile('public/js/count.json', x, finished);

  function finished(){
    console.log('Yay')
  }

    /* 
    console.log(Words[word]); */

/*     response.send(reply); */
  }

when i run the code through my script

async function counter(elemid){
  let response = await fetch("/add/"+elemid);
} 

it takes too long to respond , and sometimes it gives request timeout , is there is a faster way to do the exact same purpose

Upvotes: 0

Views: 282

Answers (1)

Deadron
Deadron

Reputation: 5279

You are not writing a response in your finished handler. This is leaving each request to only end via timeout.

In your finished function add response.end() at the end.

You can verify that this is working by ensuring that the request receives a 200 response from your server instead of timing out.

Upvotes: 1

Related Questions