0

I've created an API which I want to create a file, and after the file was written, request a log API and after its response, response relatively to the user.

I've simplified the code like this:

const express = require('express');
const router = express.Router();
const fetch = require("node-fetch");
const util = require('util');
const fs = require("fs-extra")

router.get('/works/', (req, res) => {
    logData(res)
})

router.get('/fails/', (req, res) => {
    let t = Date.now();
    const writeFile = util.promisify(fs.writeFile)
    writeFile(`./data/${t}.json`, 'test').then(function(){
        logData(res)
    })
})

function logData(res) {
    return new Promise(resolve => {
        fetch('https://webhook.site/44dad1a5-47f6-467b-9088-346e7222d7be')
            .then(response => response.text())
            .then(x => res.send('x'));
    });
}

module.exports = router

The /works/ API works fine,

but the /fails/ API fails with Error: read ECONNRESET

SalmanShariati
  • 3,873
  • 4
  • 27
  • 46
  • Does this answer your question? [How do I debug error ECONNRESET in Node.js?](https://stackoverflow.com/questions/17245881/how-do-i-debug-error-econnreset-in-node-js) – nbokmans Apr 07 '21 at 09:07
  • @nbokmans no, this couldn't help, I think there may be a problem on promise chaining – SalmanShariati Apr 07 '21 at 09:11
  • @SalmanShariati ECONNRESET means the request was aborted because it could not be completed. This usually happens server side because the request is malformed or invalid. Example, file you are trying to upload exceeds file limit. – nbokmans Apr 07 '21 at 09:12
  • 2
    How you run your code? If you are using `nodemon` it will restart the server after you change the `.json` file in this project. Make sure that your server does not restart. – Ruslan Hadyniak Apr 07 '21 at 09:53
  • 1
    `writeFile` from `fs-extra` already supports promises. You don't need to `promisify` it. Is there any console output on the server side? If yes, please add it. – derpirscher Apr 07 '21 at 10:16
  • @RuslanHadyniak the problem solved when I run the code without nodemon, so would you write this as a reply with some description, I'll mark it as the answer to help others. – SalmanShariati Apr 07 '21 at 10:29

1 Answers1

3

OP clarified in the comments that he uses nodemon to run this code.

The problem is that nodemon watches .json files too and restarts the server. So the request that changes a JSON file fails with Error: read ECONNRESET.

To prevent nodemon from restarting server when you change .json files see this.
For example, you can add nodemon.json configuration file to ignore ./data directory (make sure to restart nodemon after this file is added):

{
    "ignore": ["./data"]
}
Ruslan Hadyniak
  • 208
  • 1
  • 6