Code:
function getLocalFiles() {
let files = [];
return new Promise((resolve, reject) => {
fs.readdir('storage', (err, filenames) => {
if (err)
throw err;
filenames.forEach((filename) => {
fs.readFile('storage/' filename, 'utf-8', (err, data) => {
if (err)
throw err;
const file = {
filename: filename,
content: data
};
files.push(file);
//console.log(files); I checked that array has a files but then it returns empty
});
});
});
resolve(files);
})
}
api.get('/', async (req, res) => {
const files = await getLocalFiles();
res.send('local files:\n' files);
})
I have some files in "storage" directory and I declared a getLocalFiles() function that read the name and content of each file in this directory and pushed it to "files" array. But instead of this I got and empty array. Why files are not written to the array?
CodePudding user response:
A few pointers:
- The code you're writing would benefit a lot from using the promises version of fs (
fs/promises
). - avoid mixing promises and callbacks, and just use promises (via async/await where possible).
- I didn't change it here, but if you're gonna be running this on windows, the
/
separator won't cut it, so usepath.join('storage', filename)
instead
const fs = require('fs/promises');
async function getLocalFiles() {
let files = [];
const dir = await fs.readdir('storage')
for (const filename of dir) {
files.push({
filename,
content: await fs.readFile('storage/' filename, 'utf-8')
})
}
return files;
}
api.get('/', async (req, res) => {
const files = await getLocalFiles();
res.send('local files:\n' files);
})