Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read the content of files synchronously in Node.js?

This is what I have:

#! /usr/bin/env node  var fs = require('fs'),     files = fs.readdirSync(__dirname + '/files/'),  files.forEach(function(file) {   fs.readFile(__dirname + '/files/' + file, 'utf8', function (error, data) {     console.log(data)   }) }) 

Even though I'm using readdirSync the output is still asynchronous:

alex@alex-K43U:~/node/readFiles$ node index.js  foo 1  foo 3  foo 2 

How to modify the code so the output becomes synchronous?

alex@alex-K43U:~/node/readFiles$ node index.js  foo 1  foo 2  foo 3 
like image 664
alexchenco Avatar asked Dec 07 '15 13:12

alexchenco


People also ask

How NodeJS read the content of a file?

To get the contents of a file as a string, we can use the readFileSync() or readFile() functions from the native filesystem ( fs ) module in Node. js. The readFileSync() function is used to synchronously read the contents from a file which further blocks the execution of code in Nodejs.

How do I read a NodeJS asynchronous file?

readFileSync() method is an inbuilt application programming interface of fs module which is used to read the file and return its content. In fs. readFile() method, we can read a file in a non-blocking asynchronous way, but in fs. readFileSync() method, we can read files in a synchronous way, i.e. we are telling node.

How do I make my reader onload synchronous?

You can use the standard FileReaderSync, which is a simpler, synchronous, blocking version of the FileReader API, similar to what you are already using: let reader = new FileReaderSync(); let result_base64 = reader. readAsDataURL(file); console. log(result_base64); // aGV5IHRoZXJl...

Can NodeJS be synchronous?

For synchronous programming, you only need to focus on the call stack. This is the only part of the NodeJS environment that will be working in this case. A callback stack is a data structure that you use to keep track of the execution of all functions that will run inside the program.


1 Answers

You need to use readFileSync, your method is still reading the files asynchronously, which can result in printing the contents out of order depending on when the callback happens for each read.

var fs = require('fs'),     files = fs.readdirSync(__dirname + '/files/');  files.forEach(function(file) {   var contents = fs.readFileSync(__dirname + '/files/' + file, 'utf8');   console.log(contents); }) 
like image 163
Gazler Avatar answered Oct 05 '22 17:10

Gazler