Node.js中的未知编码错误

时间:2017-09-22 17:23:47

标签: javascript node.js server character-encoding

我是Node.js的新手并且遇到了一个错误,这个错误让我在2天内感到烦恼!

JS看起来像这样:

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.....");

这是HTML文件:

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

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

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

</html>

但我最终得到了这个错误:

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)

有人能告诉我出了什么问题,还是指出了我正确的方向?

1 个答案:

答案 0 :(得分:2)

style='margin-top: 1px;' 需要参数

fs.createReadStream

所以对于你的情况你应该像

一样写
fs.createReadStream(path[, options])