I'm coding website in node.js using express and socket.io. The server is sending to user photo and data from every file in directory using socket.emit function.
The problem with this code: The server is sending data from 2 files but image in second emit is same as first beacouse before sends first img is changing data of first file to second data.
I found this solution but it's not working. Some of the server side code:
function send(file) {
return new Promise((resolve, reject) => {
fs.readFile(dir + file, 'utf8', (err, jsonString) => {
jsonString = JSON.parse(jsonString);
buffer = ""
img = false
img_path = dir + jsonString.number
if (fs.existsSync(img_path + '.jpg')) {
fs.readFile(img_path + '.jpg', function (err, buf) {
buffer = buf
img = true
});
}
if (fs.existsSync(img_path + '.png')) {
fs.readFile(img_path + '.png', function (err, buf) {
buffer = buf
img = true
});
}
setTimeout(() => { // <---- Without wait buffer will be blank
console.log(img_path) //both times is same
data = {
number: jsonString.number,
image: img,
buffer: buffer.toString('base64')
}
socket.emit('data', data)
console.log("sended!")
resolve()
}, 100)
if (err) {
console.error(err);
return;
}
});
})
}
async function files() {
fs.readdir(dir, (err, files) => {
if (err) {
throw err
}
files.forEach(async file => {
if (file.split('.').pop() == 'json') {
await send(file)
}
})
})
}
files()
But this is not working. Thanks for help!