Is there any advantage in storing static html files in a server variable on a node-express server?

409 views Asked by At

I am running a small node-server using express and at some point I decided to store my static html-content in variables on my server instead of serving them from the disk, thinking that the server should store them in the RAM this way and thus serve them slightly faster.

However, looking for solid information on the topic I was left disappointed, and was unable to find anything on the topic. Therefore I am asking for thoughts on the topic this way (or even good reading material on the topic).

Best, Fochlac

Sample Code:

const   express = require('express')
    ,   app = express()
    ,   server = require('http').createServer(app)
    ,   server = require('http').createServer(app)
    ,   server_port = 8080
    ,   server_ip_address = 'localhost';

server.listen(server_port, server_ip_address, () => {
    console.log('listening on port '+ server_port);
});

app.use('/index', express.static('/Public/index.html'));

/*** vs ***/

const index = fs.readFileSync('/Public/index.html').toString();

app.get('/index', (req, res, next) => {
    res.status(200).send(index);
});
1

There are 1 answers

0
num8er On BEST ANSWER

if files are small, so why not?

it's better to cache files in variables to use memory io than hdd io which is cheaper.

but keep in mind to track file changes and reread it:

const staticFiles = {
  'index': fs.readFileSync(__dirname+'/Public/index.html').toString();
};
fs.watch(__dirname+'/Public/index.html', () => {
  staticFiles.index = fs.readFileSync(__dirname+'/Public/index.html').toString();
});

app.get('/index', (req, res, next) => {
    res.status(200).send(staticFiles.index);
});

but I think express-static middleware does it already.

read this: http://expressjs.com/en/starter/static-files.html and this: https://github.com/expressjs/serve-static/blob/master/index.js

but I did not saw that it's caching file to variable.



I don't care about this question because, I'm using nodejs app behind nginx, so all buffering and static file serving is done by nginx.