Reputation: 23
I am trying to read a html file to my .js file. I am using var fs = require('fs');
to read the file, when I run in my terminal, it executes, but when I browse to my local host, I get this error in the terminal:
http_outgoing.js:722
throw new ERR_INVALID_ARG_TYPE('first argument',
^
TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be of type string or an instance of Buffer or Uint8Array. Received undefined
at write_ (_http_outgoing.js:722:11)
at ServerResponse.write (_http_outgoing.js:687:15)
at ReadFileContext.callback (/Users/mac/test/demo_readfile.js:20:9)
at FSReqCallback.readFileAfterOpen [as oncomplete] (fs.js:282:13) {
code: 'ERR_INVALID_ARG_TYPE'
}
and the error in the browser is says "localhost didn't send any data". I can only assume that the local host cannot find the file, or can't open it. The HTML file is saved in the same folder as the .js file. Here is the .js file code:
var http = require('http');
var fs = require('fs');
''''''''''''''''''''''''''''''''''''''''''''''''''''''
http.createServer(function (req, res) {
//Open a file on the server and return its content:
fs.readFile('/demofile1.html', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
return res.end();
});
}).listen(8080);
and the HTML code
<html>
<body>
<h1>My Head</h1>
<p>my paragraph</p>
</body>
</html>
Upvotes: 1
Views: 15123
Reputation: 1
I'm late I'm responding if anyone else is following the ww3 course. As the error says, the ServerResponse.write accept an argument as a string. Because of the function readfile being async you get data as undefined which is it's datatype so you pass undefined to res.write(). To not getting any error just:
res.write(toString(data))
You will get then a blank page with "undefinied". This course is very old (2011 or something). We should move to something new. Javascript has grown up since then.
Upvotes: 0
Reputation: 370
Your code seems correct but there is little error in your code. your file read path must have location of your parent folder or the folder contains the file to read. you are not mentioning route to file as './' ('./demofile1.html').
try following code.
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
//Open a file on the server and return its content:
fs.readFile('./demofile1.html', function (err, data) {
console.log(data)
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write(data);
return res.end();
});
}).listen(8080);
My folder structure: [![folder structure ][1]] [1]: https://i.sstatic.net/mO9hx.png
Upvotes: 1