Pranshu Duneja
Pranshu Duneja

Reputation: 51

Unknown Encoding Error in Node.js

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?

Upvotes: 2

Views: 14859

Answers (2)

Mahmud Suberu
Mahmud Suberu

Reputation: 42

for the use __dirname you should;

first join the path

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

then

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

Upvotes: 0

Prasanna
Prasanna

Reputation: 4656

fs.createReadStream takes parameters

fs.createReadStream(path[, options])

so for your case you should write it like

fs.createReadStream(`${__dirname}/index.html`, {encoding: 'utf8'})

Upvotes: 3

Related Questions