Измените порядок вашего кода, и он будет работать нормально:
const fs = require('fs')
let folder = '../../importedFiles/data';
let files_to_read = []
let files = fs.readdirSync(folder);
let fileSchema = require('../db/models/fileUpload');
let files_to_simulate = [];
files.forEach(file => {
let fileStat = fs.statSync(folder + '/' + file).isDirectory();
if(!fileStat) {
files_to_read.push(file);
}
});
fileSchema.find({}, async function(err, files) {
files.forEach(function(file) {
files_to_read.forEach(function(directoryFile) {
var dbFile = file.name.split('.');
let dirFile = directoryFile.split('.');
if (dbFile[0] === dirFile[0]) {
console.log('saa')
files_to_simulate.push(dirFile[0]);
}
})
})
// If you want to have the result you need to call a function here
console.log(files_to_simulate)
});
Если вы хотите экспортировать, вам нужно это:
const fs = require('fs')
let folder = '../../importedFiles/data';
let files = fs.readdirSync(folder);
let fileSchema = require('../db/models/fileUpload');
// in the destination file just give it a callback
module.exports = function(callback){
let files_to_read = []
let files_to_simulate = [];
files.forEach(file => {
let fileStat = fs.statSync(folder + '/' + file).isDirectory();
if(!fileStat) {
files_to_read.push(file);
}
});
fileSchema.find({}, async function(err, files) {
files.forEach(function(file) {
files_to_read.forEach(function(directoryFile) {
var dbFile = file.name.split('.');
let dirFile = directoryFile.split('.');
if (dbFile[0] === dirFile[0]) {
console.log('saa')
files_to_simulate.push(dirFile[0]);
}
})
})
// If you want to have the result you need to call a function here
callback(files_to_simulate)
});
}
Здесь вы можете прочитать о Асинхронный в JavaScript