Node.js

How to Read Files in Node.js

About how to read files in the Node.js programming language. Reading and writing files in programming is one of the basics, so it's definitely something you want to learn.

Shou Arisaka
1 min read
Oct 30, 2025

<> About how to read files in the Node.js programming language. Reading and writing files in programming is basic, so itโ€™s definitely something you want to learn. </>

Place a function like main() inside the callback as follows and write code to process the file text within main().


var fs = require('fs');
var path = require('path');

var content;

console.log(__line);

fs.readFile('tmp.txt', 'utf8', function(err, content) {
    console.log(content);
});

console.log(__line);

fs.readFile('tmp.txt', 'utf8', function(err, data) {
        content = data;
    main() ;
});

console.log(__line);

function main(){
    console.log(content);
}

console.log(__line);

Output

Image

18
24
31
37
something ++inserted++ here.

something ++inserted++ here.

javascript - Get data from fs.readFile - Stack Overflow

Share this article

Shou Arisaka Oct 30, 2025

๐Ÿ”— Copy Links