how to cache in node js?

806 views Asked by At

I am new to nodejs. I have one API which returns file in response. Currently when I get the request, I read the file every time and send it. Can we do caching in memory to speed up?

I checked this package. can we use this package to speed up. https://www.npmjs.com/package/memoizee

 server.get('/user', (req, res) => {
    res.sendFile(path.join(distFolder,'user','index.html'))
  });

Current what I am doing

Right now I am running node server.when /user request come on I am sending html file .while is working fine.

can we optimise this ? can we cache this file ?

1

There are 1 answers

7
Jaromanda X On BEST ANSWER

A simple approach

import { readFileSync } from "node:fs";

const cache = {};
const simpleCache = path => {
    if (!cache[path]) {
        cache[path] = readFileSync(path).toString();
    }
    return cache[path];
};
server.get('/user', (req, res) => {
    res.send(simpleCache(path.join(distFolder,'user','index.html')));
});