Access variable from sync and async in nodejs

52
August 21, 2019, at 03:00 AM

I'm creating a nodejs server that has to do a few things:

  1. Log data from a serial port
  2. While downloading a file from a url
  3. Log results after download
  4. Send both data streams to a client when requested

Here's a reduced version of my code (this is from memory, there may be syntax errors):

const express = require('express'); 
const serialport = require ('serialport'); 
const http = require('http'); 
const fs = require('fs'); 
const bodyParser = require('body-parser'); 
 
const port = new SerialPort('/dev/tty/port', { 
  baudRate: 57600 
}); 
 
let output = []; 
let app = express(); 
 
app.use(bodyParser.json()); 
 
app.post('/download', function(req, res){ 
  res.send('Downloading...'); 
  let fileUrl = req.body.url; 
  const file = fs.createWriteStream("fileName"); 
  const request = http.get(fileUrl, function(response) { 
    response.pipe(file); 
   
    response.on('end', function(){ 
      output.push("Downloaded"); 
      //Do a lot of stuff 
    } 
  }); 
}); 
 
app.get('/log', function(req, res){ 
  res.send(output.shift()); 
}); 
 
port.on('data', function(data){ 
  output.push(data); 
}); 
 
app.listen(88);

The problem is that I can't add anything to the output list after downloading the file because it's asynchronous. How can I send logs from both sources while they're still running? One alternative is downloading the file synchronously, but I haven't found a way to do so. My program can't have more than one client so I have no need for asynchronous functions at any point.

A catch is that I'm developing this on an internal network that doesn't have access to the internet, so downloading dependencies is a huge pain I would like to avoid as much as possible. Any help is appreciated, thanks!

READ ALSO
How to handle promises in nested loop

How to handle promises in nested loop

I have an array of objects like this:

21
How to stub require('firebase-admin').auth().getUserByEmail() with sinon?

How to stub require('firebase-admin').auth().getUserByEmail() with sinon?

Could you please share some example of Sinon stub for firebase-admin authentificationThe challenge is to initialize firebase admin app for further stubs

52
Turning off Strict Mode in Angular?

Turning off Strict Mode in Angular?

I'm running into this issue and I'd like to turn off strict mode to get around it

34
How to run an isolated Node.js environment inside browser?

How to run an isolated Node.js environment inside browser?

I am trying to use isomorphic-git to perform git clone command on browser-sideBut due to adhering to the same-origin policy, I cannot send a cross-origin request to our company's GitLab, if no cors-proxy I can use

54