-1

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 ?

Deidara
  • 667
  • 2
  • 13
  • 28

1 Answers1

0

Send the response only when you have all the data. See the code below, which waits until the length of the result array is 4 (the number of iterations of the loop):

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)
       remaining -= 1
       if (result.length === 4) {  // all done
        res.send(result)
       } 
     })
  }
}
user94559
  • 59,196
  • 6
  • 103
  • 103