How to read file contents 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)
  })
})

Despite what 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 change the code so that the output becomes synchronous?

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

foo 2

foo 3
+4
source share
3 answers

You need to use it readFileSync, your method still reads files asynchronously, which can lead to the content being corrupted, depending on when the callback occurs 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);
})
+12
source

This is because you are reading the file asynchronously. Try:

#! /usr/bin/env node

var fs = require('fs'),
    files = fs.readdirSync(__dirname + '/files/'),

files.forEach(function(file) {
  var data = fs.readFileSync(__dirname + '/files/' + file, 'utf8');
  console.log(data);
});
+2
source
+1

Source: https://habr.com/ru/post/1618896/


All Articles