2

I am new to Node.js and stuck on an error which is irritating me from 2 days!

The JS looks like this:

var http = require('http');
var fs = require('fs');

var server = http.createServer(function(req, res) {
 console.log("A request was made of url : " + req.url);
 res.writeHead(200, { 'Content-Type': 'text/html' });
 var data = fs.createReadStream(__dirname, '/index.html', 'utf8');
 data.pipe(res);
});
server.listen(4242);
console.log("Server is running.....");

And this is the HTML file:

<!DOCTYPE <html>
<html lang="en">

<head>
<meta charset="UTF-8">
<title>Index Website</title>
</head>

<body>
<h1>Some HTML</h1>
</body>

</html>

But I end up getting this error:

string_decoder.js:13
throw new Error(`Unknown encoding: ${enc}`);
^

Error: Unknown encoding: /index.html
at normalizeEncoding (string_decoder.js:13:11)
at new StringDecoder (string_decoder.js:22:19)
at new ReadableState (_stream_readable.js:99:20)
at ReadStream.Readable (_stream_readable.js:108:25)
at new ReadStream (fs.js:1907:12)
at Object.fs.createReadStream (fs.js:1885:10)
at Server.<anonymous> (G:\Docs\Node.js\server.js:7:19)
at emitTwo (events.js:106:13)
at Server.emit (events.js:191:7)
at HTTPParser.parserOnIncoming [as onIncoming] (_http_server.js:546:12)

Can someone tell me what went wrong, or point me in the right direction?

7
  • You seem to use fs.createReadStream incorrectly. Commented Sep 22, 2017 at 17:27
  • Can you explain the mistake please ? Commented Sep 22, 2017 at 17:30
  • fs.createReadStream takes parameters fs.createReadStream(path[, options]) so for your case you should write it like fs.createReadStream(`${__dirname}/index.html`, {encoding: 'utf8'}) Commented Sep 22, 2017 at 17:47
  • Thank You so much Sir ! That solved my problem and I am feeling so much relaxed now :) Commented Sep 22, 2017 at 17:57
  • I will put a comment with this answer. Please mark it correct. Commented Sep 22, 2017 at 18:30

2 Answers 2

3

fs.createReadStream takes parameters

fs.createReadStream(path[, options])

so for your case you should write it like

fs.createReadStream(`${__dirname}/index.html`, {encoding: 'utf8'})
Sign up to request clarification or add additional context in comments.

Comments

0

for the use __dirname you should;

first join the path

const indexPath = path.join(___dirname, "index.html");

then

const data = fs.createReadStream(indexPath, 'utf8');

Comments

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.