Home > Blockchain >  how to cache in node js?
how to cache in node js?

Time:08-25

I am new nodejs .I am reading and sending every time .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 ?

CodePudding user response:

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