Categories
JavaScript Answers

How to require file as string with Node.js?

Spread the love

Sometimes, we want to require file as string with Node.js.

In this article, we’ll look at how to require file as string with Node.js.

How to require file as string with Node.js?

To require file as string with Node.js, we can use fs.readFileSync.

For instance, we write

const fs = require('fs')
const path = require('path')

const css = fs.readFileSync(path.resolve(__dirname, 'email.css'), 'utf8')

to call fs.readFileSync to read the file at path returned by path.resolve(__dirname, 'email.css').

We specify to read the file as a 'utf8' encoded text file.

readFileSync reads the file synchronously just like require.

Conclusion

To require file as string with Node.js, we can use fs.readFileSync.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *