Search code examples
javascriptnode.jscachingnode-modulesmemoizee

how to cache in node js?


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 ?


Solution

  • 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')));
    });