lukassz
lukassz

Reputation: 3340

Node how to pass file to http.write method?

I woudl like to print file to res.write() method but I get error:

TypeError: First argument must be a string or Buffer

My code:

var fs = require("fs");
var http = require("http");


http.createServer(function (req, res){

    res.write(getData());
    res.end();

}).listen(3333);


function getData(){
    fs.readFile('testfs.txt', function(err, data){

        if(err)
        {
            console.log("Error: " + err);
        }else {
            console.log(data.toString());
            return data.toString();
        }

    });
}

What's the problem?

Upvotes: 0

Views: 34

Answers (3)

robertklep
robertklep

Reputation: 203359

Alternatively, you can use streams:

const http = require('http');
const fs   = require('fs');

http.createServer((req, res) => {

  fs.createReadStream('testfs.txt')
    .on('error', (e) => {
      console.log('Error:', e);
      res.statusCode = 500;
      res.end();
    })
    .pipe(res)


}).listen(3333);

Upvotes: 2

Nonemoticoner
Nonemoticoner

Reputation: 648

res.write didn't get string nor buffer because your function getData wasn't asynchronous. Here's the fix I hope will solve your problem:

http.createServer(function (req, res){

    getData(function(data){
        res.write(data);
        res.end();
    }));

}).listen(3333);

function getData(cb){
    fs.readFile('testfs.txt', function(err, data){

        if(err)
        {
            console.log("Error: " + err);
        }else {
            cb(data.toString());
        }

    });
}

Where cb argument is a callback function obviously.

Upvotes: 2

uglycode
uglycode

Reputation: 3082

Do it the other way around; just call getData and pass in response, then when the file is loaded, call response.end(string).

Upvotes: 0

Related Questions