0

I have created a simple filereader method in node.js that takes in an html file in the same folder. However, when I try to launch it on my localhost, I receieve the message: throw new TypeError<'First argument must be a string or Buffer'>;

My node.js file is:

var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
  fs.readFile('demofile1.html', function(err, data) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write(data);
    res.end();
  });
}).listen(8080);

And my HTML code is simple as well:

<html>
<body>
<h1>My Header</h1>
<p>My paragraph.</p>
</body>
</html>

If someone could please provide some insight, it would be much appreciated. I looked on both Google and StackOverflow and no solutions fixed my problem. Other node programs like outputting "Hello World" or displaying the date and time work on my localhost.

3
  • You should add if (err) { console.error(err); } to your readFile callback, it's probably a path issue Commented Aug 2, 2017 at 23:48
  • I added in the code snippet you mentioned, but nothing changes. If you have not done so, could you run it yourself and see what happens? Commented Aug 3, 2017 at 0:06
  • Nothing wrong with your code, maybe the type in file name, because I tried with typo and the reusult islike yours. Commented Aug 3, 2017 at 1:55

1 Answer 1

1

Most likely err is set and data is undefined. You should always check for errors first.

Sign up to request clarification or add additional context in comments.

3 Comments

Could you give me an idea of how to define data?
You don't. It's what is passed to your callback function.
Checking for errors did not help, but I did think about why data would be undefined and I realized that you need to explicitly delineate the file path in order for the .js file to find it. I had assumed that since they were in the same folder, it would already know where it would be located. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.