SalmanShariati
SalmanShariati

Reputation: 3893

NodeJS API response fails after fs.writefile

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

Upvotes: 0

Views: 496

Answers (1)

Ruslan Hadyniak
Ruslan Hadyniak

Reputation: 208

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"]
}

Upvotes: 3

Related Questions