fs.readFileSync() method in Node.js

Youn Hee Pernling Frödin
1 min readDec 11, 2020

I know that my Python/Pandas story about pd.read_csv() has been popular. And based on that I have decided to write a very basic story about how to read a text-file in JavaScript/Node.js.

I first encountered the problem when I had to read the data for the Advent of Code problems. And I’m glad I found out how to get hold of the data. Would have been hard to start solving the problems otherwise.

This is the syntax that you have to use:

fs.readlinkSync(path[, options])

Where the path can be a string, buffer or URL, in other word how to get hold of the file that you want to read.

Options can be an object or a string. Here you can specify an optional parameter that will affect the output. The optional parameter is encoding and default is utf8.

Code example:

let myContent = fs.readFileSync(‘input.txt’, ‘utf8’);

The goal is that the data in your input text-file should be read and stored in the myContent variable.

However, this will not work. There is one more thing we need to do before running above line of code. We need to import the filesystem module.

const fs = require('fs');

This is what it will look like in the end:

const fs = require('fs');
let myContent = fs.readFileSync(‘input.txt’, ‘utf8’);

I hope this can be to some help for someone!

You can read more about it in the Node.js documentation here.

--

--