The server needs to respond to a http get
with all the data from separate file. Here I am using a csv parser.
function sendFileData(req, res) {
var result = []
// Convert an csv file to Json entries
for (var i = 0; i < 4; i++) {
var dataArray = []
csvFilePath = ...
time = '"'
value = '""'
fs.createReadStream(csvFilePath)
.pipe(csv({headers: ['date', 'time', 'value']}))
.on('data', function (data) {
date = ...
time = ...
value = ...
dataArray.push('{' + date + time + value + '}')
})
.on('end', function () {
var sensorData = '[' + dataArray + ']'
result.push(sensorData)
})
}
res.send(result)
}
Since the for loop takes some time to finish, the result is always []
, so I consider to add setTimeout()
and a callback function, but I feel the setTimeout
is a bad approach.
function sendFileData(req, res, callback) {
var result = []
// Convert an csv file to Json entries
for (var i = 0; i < 4; i++) {
var dataArray = []
csvFilePath = ...
time = '"'
value = '""'
fs.createReadStream(csvFilePath)
.pipe(csv({headers: ['date', 'time', 'value']}))
.on('data', function (data) {
date = ...
time = ...
value = ...
dataArray.push('{' + date + time + value + '}')
})
.on('end', function () {
var sensorData = '[' + dataArray + ']'
result.push(sensorData)
})
}
setTimeout(function () {
callback(res, result)
}, 1000)
}
function sendData (res, result) {
res.send(result)
}
// calling function
sendFileData(req, res, sendData)
Is there a better way to send all the data after the csv-parser finished reading ?