NodeJS: Files only update after restarting the express server

Issue

I am using nodejs with express for a small backend application which just returns a json file from another directory.

Example scenario:
My json files are in the directory "/var/data", so e.g. "/var/data/hello.json". If I start the nodejs backend with "node index.js" everything works as expected.

But if I change the contents of a json file, I still get the old version from the backend.

How can I set this up, so that my backend nodejs server detects these file changes in another directory without restarting it?

index.js:

const express = require('express');
const fs = require('fs');

const app = express();
app.use(express.json());

const myDataPath = "/var/data/";

app.get("/:id", (request, response) => {
    let id = request.params.id;
    let path = myDataPath + id + ".json";

    if (fs.existsSync(path)) {
        response.json(require(path));
    } else {
        response.sendStatus(404);
    }
});

Solution

Issue is likely with using "require", this is a guess, but maybe require doesn’t run twice for optimization reasons.

const express = require('express');
const fs = require('fs');

const app = express();
app.use(express.json());

const myDataPath = './var/data/';

app.get('/:id', (request, response) => {
    let id = request.params.id;
    let path = myDataPath + id + '.json';

    console.log(path);

    if (fs.existsSync(path)) {
        response.json(JSON.parse(fs.readFileSync(path)));
    } else {
        response.sendStatus(404);
    }
});

app.listen(1025);

The above code snippet worked on my testing example, I used readFileSync to retrieve the data, uncached, and the response changes when the file is modified, without needing to restart the app.

Answered By – MTN

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published