简体   繁体   中英

Node.js pretty basic but sneaky error

Gooday guys, I've a problem with Node.js. I have recently started to learn it from w3schools. But when I copied this piece of code, than the following exception occurs:

TypeError: First argument must be a string or Buffer

I have index.html file which looks pretty basic. It shouldn't be a mess for the code.

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

Don't ignore errors! ( it makes everything worse)

fs.readFile('index.html', function(err, data) {

This either passes data and err will be null , or if an error occurs data will be null and err is an Error . When the later happens you ignore it and do

res.write(data);

which won't work as data is null and you can't send null to the client ( only Buffers or Strings as said in the error). So what to do? Well add an error handler:

fs.readFile('index.html', function(err, data) {
 if(err)
   return res.write(err.message);

 res.writeHead(200, {'Content-Type': 'text/html'});
 res.write(data);
 res.end();
});

So now you will probably get the real error which is

File not found

So you may check if youve got an index.html file.

It's happening mostly because of either res.write() or res.end() either one of it accepts string as its first argument try using res.send(data) will work fine. Have a good day. Happy Learning NodeJS

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM