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?