简体   繁体   中英

How to create and send html file to client in nodeJS from backend(express)?

Im trying to create a file from a string that contains html content for example:

const html = " <!DOCTYPE html> <html> <body> <p>example</p> </body> </html> ";

Now how would you create a read stream and pipe it to the response without creating the file locally?

If you are using express you can do the following

// as string (for short strings)
router.get('/my-html', function (req, res) {
  const html = "<!DOCTYPE html> <html> <body> <p>example</p> </body> </html>";
  
  res.type('html');
  res.send(html);
})

Or

// as stream (for large strings)
router.get('/my-html', function (req, res) {
  const html = "<!DOCTYPE html> <html> <body> <p>example</p> </body> </html>";
  const readStream = Readable.from(html)
  
  res.type('html');
  readStream.pipe(res);
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM