0

I am new to Node JS. Please help me to understand what am I doing wrong in the POST request. Sometimes my POST request is getting successfully resolved but sometimes it is giving me ECONNRESET.

I am sharing my app.js and file reader wrapper module.

GET is working perfectly fine.

Below is my App.js

const express = require('express');
const FileReader = require('./readFS');
const app = express();
const FS = new FileReader();

const port = 3000;
app.listen(3000, '127.0.0.1', () => {
  console.log(`App running on port ${port}`);
});
app.use(express.json());

app.get('/api/v1/tours', (request, response) => {
  const data = FS.read(`${__dirname}/dev-data/data/tours-simple.json`).then(
    (data) => {
      response.status(200).json({
        status: 'success',
        results: data.length,
        data: {
          tours: data,
        },
      });
    }
  );
});
app.post('/api/v1/tours', (request, response) => {
  (async (req, res) => {
    const tours = await FS.read(`${__dirname}/dev-data/data/tours-simple.json`);
    const newID = tours[tours.length - 1].id + 1;
    const newTour = Object.assign({ id: newID }, req.body);
    tours.push(newTour);
    console.log('File written Started');
    await FS.write(
      `${__dirname}/dev-data/data/tours-simple.json`,
      JSON.stringify(tours)
    );
    console.log('File written Successfully');
    res.status(200).send('Created Succesfully');
  })(request, response);
});

File Reader Module:


module.exports = class {
  constructor() {
    this.tours = [];
  }

  read(path) {
    return new Promise((resolve, reject) => {
      if (this.tours.length > 0) {
        resolve(this.tours);
      }
      fs.readFile(path, 'utf-8', (err, data) => {
        if (err) reject(er);
        this.tours = Object.assign(JSON.parse(data));
        resolve(this.tours);
      });
    });
  }
  write(path, data) {
    return new Promise((resolve, reject) => {
      if (data.length <= 0) reject('Data is empty');
      fs.writeFile(path, data, (err) => {
        if (err) reject('Could not write');
        resolve('Done');
      });
    });
  }
};
Amila Senadheera
  • 12,229
  • 15
  • 27
  • 43
user1071309
  • 61
  • 1
  • 7

1 Answers1

0

Explanation of the error I was encountering

My issue with occasionally receiving ECONNRESET when POSTing to my listening endpoint was caused by the endpoint automatically restarting after each successful POST of a file to that same endpoint.

OldBuildingAndLoan
  • 2,801
  • 4
  • 32
  • 40
user1071309
  • 61
  • 1
  • 7
  • This does not provide an answer to the question. If you'd like to add more information relating to the question, edit the original post to provide any extra information. – Tyler2P Feb 12 '22 at 14:46
  • I would be happy to know more info on this. I can understand that, the answer I posted does not give the resolution. But thats the cause of the problem. You comments on the resolution would be really helpful @Tyler2P – user1071309 Feb 13 '22 at 07:43