0

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

1 Answer 1

1

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.

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

1 Comment

thnx, that helped a alot, there is function that renders the count to some DOM element ``` async function renderCount(clicked) { let response = await fetch('js/count.json'); let data = await response.json(); console.log(data); for (i = 0; i < data.length; i++){ if (data[i].type == clicked){ document.getElementById("lastHandeled").innerText = data[i].type + " " +data[i].count; } } } ``` sometimes when i click the element , it console logs this error script.js:4 Uncaught (in promise) SyntaxError: Unexpected end of JSON input at renderCount

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.