Search code examples
node.jsexpressweb-applicationsservercode-generation

NodeJS Express — Serve generated index.html public file without saving it


When using express, the expectation is that you'll serve a public directory.

const app = express();
app.use('/', express.static('./public/'));

Is there a way I could serve a generated file instead? For my application, it would be much more convenient if I could build the index.html directly, then serve that 'file' directly from memory, without having to save it just to then serve it via 'use'.


Solution

  • the expectation is that you'll serve a public directory

    I don't think that is the expectation at all. Many applications just use routes instead making a REST micro service.

    There are two ways you can do what you want to do.

    1. Use a templating engine with NodeJS and just res.render() the template. Check this out for more information, even though the article is using .pug you can use these ones as well. Popular ones are ejs, handlebars

      app.get('/', function (req, res) {
          res.render('index', { title: 'Hey', message: 'Hello there!' })
      })
      
    2. Or you can write everything inside res.send() for example:

      app.get('/', function (req, res) {
          //set the appropriate HTTP header
          res.setHeader('Content-Type', 'text/html');
      
          //send multiple responses to the client
          res.send('<h1>This is the response</h1>');
      });