Node.js — Read File Content as String

You may need to read files from a local hard disk in your Node.js project. A typical use case when interacting with files is to read the content as a string. This tutorial shows you how to read a file’s content as a string using Node.js

Node.js Series Overview

Read a File’s Content as a String

Node.js comes with the fs module. This module contains a readFile method. This readFile method accepts two arguments: the file path and options how to return the contents. You can return the file content as a string using the string value 'utf8' as the encoding option.

Here’s a content method reading a file from the given file path and returning the content of this file:

const { readFile } = require('fs/promises')

/**
 * Returns the content of the given file `path` as a string.
 *
 * @param {String} path
 *
 * @returns {String}
 */
async function content(path) {  
  return await readFile(path, 'utf8')
}

const text = await content('./existing-file.txt')  
// 'Hello Marcus. Dude, you look super sharp today :)'

Use the @supercharge/fs Package

I’m the maintainer of the @supercharge/fs package providing convenient file system utilities. This package comes with a handy content(path) method reading and returning the content of the given file path as a string:

const Fs = require('@supercharge/filesystem')

const text = await Fs.content('./existing-file.txt')  
// 'Hello Marcus. Dude, you look super sharp today :)'

Enjoy!


Mentioned Resources

Explore the Library

Find interesting tutorials and solutions for your problems.