简体   繁体   中英

running into node.js TypeError: First argument must be a string or Buffer with the simplest possible script

So I ran into an error reading TypeError: First argument must be a string or Buffer when running a node.js script, and after a lot of stackoverflow and tutorial googling I couldn't find the solution, so I created sample code literally copy-pasted from the W3Schools node.js tutorial, which still returns the TypeError. The code in question is:

var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
  //Open a file on the server and return it's content:
  fs.readFile('demofile1.html', function(err, data) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write(data);
    return res.end();
  });
}).listen(8080);

demofile1.html:

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

the console still returns the error

TypeError: First argument must be a string or Buffer
    at write_ (_http_outgoing.js:642:11)
    at ServerResponse.write (_http_outgoing.js:617:10)
    at ReadFileContext.callback (*file path*)
    at FSReqWrap.readFileAfterOpen [as oncomplete] (fs.js:420:13)

I'm assuming that something has to be wrong with my environment, but I've installed node.js and run npm install fs manually, all to no avail. I can run other node.js servers fine, but the error comes when I try to read an html file using fs.

Thanks

I don't recommend W3Schools as a respectable tutorial source, and this is a great example why not: they don't teach good habits like error handling. Because you copied and pasted the example as they had it, your error is rather cryptic. However with good error handling, your error would be caught earlier and give you a much better indication of what went wrong.

With that in mind, try this:

var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
  //Open a file on the server and return it's content:
  fs.readFile('demofile1.html', function(err, data) {
    if (err) throw err; // crash with actual error instead of assuming success
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write(data);
    return res.end();
  });
}).listen(8080);

It looks that demofile1.html is not found on the same path as where you are starting you server.

I would recommend to:

  1. Try placing the server.js (or whatever you named your js file) in the same path as your demofile1.html and try again
  2. If you need them on subfolders, try navigating with absolute paths, or use some npm extension like rootpath
  3. In the fs callback, try logging data, it is also a good practice to use existsSync() to be sure that your app doesn't crash

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