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
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.
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.
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...
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.
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); })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With