Use Require for a File String in Nodejs

Posted on October 4, 2021

Usually to include a file source in Node.js there's the fs module to work with the file-system:

const fs = require('fs')

const src = fs.readFileSync('./myFile.html', 'utf-8')

But, there in some situations, such as in ephemeral file-system in serverless stack, fs might create some trouble.

An alternative is to require the resource in the same way you do with .js and .json files.

Here a possible solution for string-based files, such as .html files:

const src = require('./myFile.html.json')

where 'myFile.html.js' is the html source compiled this way at pre-build time:

const fs = require('fs')
const html = fs.readFileSync('./myFile.html', 'utf-8')

const srcjs = JSON.stringify({html})
const html = fs.writeFileSync('./myFile.html.json', srcjs, 'utf-8')

This way you can include the string source and use this way:

const src = require('./myFile.html.json')
console.log(src.html) // the html file source