Search code examples
node.jshttpresponse

Node static file server, how to make response work in async callback?


I wrote this function that is triggered when I get a request on my node server, it works perfectly and it sends back a file that automatically starts to download.

function(req, res) {
  // … other code …

  try {
    const fileContent = fs.readFileSync(fullPath, 'utf-8');

    res.writeHead(200, {
      'Content-Type': 'text/plain',
      'Content-Disposition': `attachment; filename="${fileName}"`,
    });
    res.end(fileContent);
  } catch (err) {
    res.writeHead(404);
    res.end();
  }
}

Now I want to rewrite it using the readFile method so I tried something like this instead:

function(req, res) {
  // … other code …

  fs.readFile(fullPath, 'utf-8', function(err, data) {
    if (err) {
      res.writeHead(404);
      res.end();
      return;
    }

    res.writeHead(200, {
      'Content-Type': 'text/plain',
      'Content-Disposition': `attachment; filename="${fileName}"`,
    });
    res.end(data);
  });
}

But now it always returns a 404 error, I think the function exits before the response is ready, so it discards the response that happens too late? How can I make it work?

Please don't suggest using third party libraries, as this is not what I'm asking. I want to do this with native modules only.

Thanks in advance.

using node 10.7.0


Solution

  • The problem is actually earlier in the code, I just forgot to return inside an if statement:

    function onRequest(req, res) {    
      // … other code …
    
      if (someCondition) {
        functionOfTheOriginalPost(req, res);
        return;
        // ^-- This is the return that I forgot so it 
        // was jumping down in the "404" area
      }
    
      res.writeHead(404);
      res.end();
    }
    
    http.createServer(onRequest).listen(3000);
    

    Thanks to @Paul that made me think and realize the error.