0

Working on a file transfer utility and having a mess of a time getting the transfers done correctly.

I have folder watching done with Chokidar, and on add in Chokidar, I create a file object added to an array. Each object looks like this:

l.files.push({
  dateAdded: Date.now(),
  fileName: fileName,
  filePath: filePath,
  fullPath: p
  });

and the client checks in, get's the number of files available for download, then makes an HTTP Request for each of the files:(enclosed in object)

getFile: (loc, home) => {
  var connection = home + 'files/?loc=' + loc;
  h.get(connection, (res) =>{
    let filePath = config.thisIncoming;
    console.dir(res.body); 
  });   
}

home is the baseUrl for the api call, loc is a location identifier for the API to find.

The Express endpoint is setup to respond to the call like this:

app.get('/files', (req, res) => {
  // console.dir(req);
  for( let f of filePaths){
    console.dir(f);
    if((f.name === req.query.loc)&&(f.files.length > 0)){
      let file = f.files.pop();
      var fileName = file.fileName;
      fs.readFile(file.fullPath, (err, dat) => {
        if(err){
          console.log(err);
          res.send({status: 'NO FILES'});
        }else{
         if(dat){
            console.log(dat);
            res.send({name: fileName, data: dat});
          }
        }
      });
      }
    }
});

I didn't want to go the res.download() or res.sendFile() methods as I wanted to be able to send the file name along with the data in the file. I've set it up to send a buffer, but on the client side, it logs undefined to the console where it should log the buffer data.

Is there a better way to do this? Is there a library that can help with this? What would be a proper/better way to do this?

Chris Rutherford
  • 1,592
  • 3
  • 22
  • 58
  • First off, `res.send()` accepts a string only so you can't send a javascript object with that. You could send JSON with `res.json()`, but that does not handle binary data if your file data is not a string itself. Though I don't know the details myself, I suspect the proper way to do this is by formatting a response as MIME part where you can specify the filename in the MIME headers and then use an appropriate MIME encoding for the file. – jfriend00 Aug 18 '17 at 17:38
  • Been looking at this answer, and I like the idea of using streams and sockets to handle this over Http, and I think I almost have it.https://stackoverflow.com/questions/39335686/what-is-the-most-efficient-way-of-sending-files-between-nodejs-servers – Chris Rutherford Aug 21 '17 at 14:27

0 Answers0