I am trying to read the contents of several files in Node.js using promises. Since the standard
fs
fs-extra
fs
const fse = require('fs-extra')
const filePath = './foo.txt'
fse.readFile(filePath, 'utf8')
.then(filecontents => {
return filecontents
})
.then(filecontents => {
console.log(filecontents)
})
fse.readdir()
path.join
.map()
fse.readFile()
.map()
const fse = require('fs-extra');
const path = require('path');
const mailDirectory = './mails'
fse.readdir(mailDirectory)
.then(filenames => {
return filenames.map(filename => path.join(mailDirectory, filename))
})
.then(filepaths => {
// console.log(filepaths)
return filepaths
.map(filepath => fse.readFile(filepath).then(filecontents => {
return filecontents
}))
})
.then(mailcontents => {
console.log(mailcontents)
})
fse.readFile()
.map()
[ Promise { <pending> },
Promise { <pending> },
Promise { <pending> },
Promise { <pending> },
Promise { <pending> } ]
fse.readFile()
You have an Array of Promises. You should wait on them using Promise.all()
:
const fse = require('fs-extra');
const path = require('path');
const mailDirectory = './mails'
fse.readdir(mailDirectory)
.then(filenames => {
return filenames.map(filename => path.join(mailDirectory, filename))
})
.then(filepaths => {
// console.log(filepaths)
return filepaths
.map(filepath => fse.readFile(filepath).then(filecontents => {
return filecontents
}))
})
// Promise.all consumes an array of promises, and returns a
// new promise that will resolve to an array of concrete "answers"
.then(mailcontents => Promise.all(mailcontents))
.then(realcontents => {
console.log(realcontents)
});
Also, if you don't want to have to have an additional dependency on fs-extra
you can use node 8's new util.promisify()
to make fs
follow a Promise oriented API.