0

do you have any idea why this code:

var http = require('http');
var fs = require("fs");
var fileDir = "file.txt";
var port = 8080;
var chunk;

var readContent = (directory) => {
    fs.readFile(directory, (err, response) => {
        if(err) {
            throw(err);
        } else {
            return response.toString();
        }
    });
};

http.createServer((request, response) => {
    var content = readContent(fileDir);
    console.log("Someone is visiting: ", request.url);
    response.write(content);
    response.end();
}).listen(port, function() {
    console.log("The server is listening in port: " + port);
});

I think that the error lies on the var content = readContent(fileDir); part.

Throws up this exception:

_http_outgoing.js:447
    throw new TypeError('first argument must be a string or Buffer');
    ^

TypeError: first argument must be a string or Buffer

1 Answers1

1

readContent does not return any value, so you're passing undefined to response.write(). You need to use callbacks properly, or switch to fs.readFileSync (not recommended)

mdickin
  • 2,245
  • 18
  • 26