Reputation: 5
I have an arbitrary number file paths stored in an array as strings.
I need to read these files in series (i.e. finish reading one file before starting reading the next one), and output the file length after each file read. And after finish reading all files, print 'done'
.
I'm only allowed to use fs.readFile
and native Javascript. No fs.readFileSync
or any other module is allowed. Also, I'm on Node v6, so I can't use async/await.
Is there any way to implement the functionality, following the constraints?
Upvotes: 0
Views: 891
Reputation: 734
You don't need any fancy stuff like promises, async/await, generators to achieve that.
function readAllFiles(list) {
if(list.length == 0) return
console.log('reading ', list[0])
return fs.readFile(list[0], function (err, file) {
if (err) console.error(err); // report the error and continue
console.log('list[0] length:', file.length); // report the file length
readAllFiles(list.slice(1, list.length))
})
}
var l = ['1', 'foo', 'bar']
readAllFiles(l)
Upvotes: 4
Reputation: 714
Try use generators
.
In example code replace acync function to reading files.
// emulate async action
const stt = (resolve, str) => {
setTimeout(
() => {
console.log(str);
resolve(str);
},
2000
);
}
// Create array of functions that return Promise
const arrFunc = ['foo', 'bar', 'baz', 'qux']
.reduce(
(acc, str) => {
acc.push(() => {
return new Promise(resolve => {
stt(resolve, str);
});
});
return acc;
}, []
);
function* generator() {
for (let func of arrFunc) {
yield func();
}
}
const iterator = generator();
function quasiCo(generator, value) {
const next = generator.next();
console.log(next);
if (!next.done) {
next.value.then(res => {
quasiCo(generator, res);
});
}
}
quasiCo(iterator);
Upvotes: 0
Reputation: 944520
Read files synchronously with fs.readFile in Node?
No.
Asynchronous functions are asynchronous.
They can't be turned into synchronous functions.
Even if you could use await
(which you've ruled out), it would still be asynchronous just with syntax that let you write code in a synchronous style within a wider context that is still asynchronous.
Much of JavaScript is asynchronous. Embrace it. Lean to use Promises. Don't try to fight it.
I need to read these files in sequence (i.e. finish reading one file before starting reading the next one), and output the file length after each file read. And after finish reading all files, print 'done'.
Write a recursive function that iterates along an array. When you've read the file, either increment the iterator and recurse or print done depending on if you are at the end of the array or now.
Upvotes: -1