Eximorp
Eximorp

Reputation: 311

Sails.js: 200 response is sent before I want to send actual response

Using Sails.js 1.2.3, I'm trying to send some data from a file as a response to GET request, either over HTTP or WebSockets. No matter if I access the file synchronously or asynchronously in the controller Sails sends 200 OK response before I'm able to send actual needed response. Initially I've tried piping the file to the response, unsuccessfully:

fn: async function() {
    var fs = require("fs");
    let filename = `foo.bar`;
    let file = require("path").resolve(
      sails.config.appPath,
      `.tmp/${filename}`
    );
    let filestream = fs.createReadStream(file);
    filestream.pipe(this.res);
}

This way I get 'write after end' error and 200 OK response (with no data) is sent to client right before this error occurs.

If I do it synchronously, like:

     ...
      var offset = 0;
      var chunkSize = 2048;
      var chunkBuffer = new Buffer(chunkSize);

      var fd = fs.openSync(file, "r");
      var chunk = fs.readSync(fd, chunkBuffer, 0, chunkSize, offset);
      this.res.send(chunkBuffer);

...the 200 OK response (with no data) is sent before I reach this.res.send(). There must be some automatic response handling I'm unaware of that sends 200 OK before I can do anything useful in the controller. How do I go about not sending any response until I explicitly say this.res.send or this.res.end after obtaining data I need to send? Thanks!

Upvotes: 1

Views: 180

Answers (1)

Tirenn
Tirenn

Reputation: 21

because that is async function, so you must add await. if you dont add await, the next line will be executed because non-blocking

var fd = await fs.openSync(file, "r");
var chunk = await fs.readSync(fd, chunkBuffer, 0, chunkSize, offset);

Upvotes: 2

Related Questions