createReadStream()
功能比性能更好
readFile()
,因为
createReadStream()
读取和写入卡盘中的数据
读取文件()
读取文件()
函数可能需要更长的时间才能进一步处理数据。因此,我选择使用
createReadStream()
功能如下。
http.createServer( function (request, response) {
var pathname = url.parse(request.url).pathname;
var readerStream = fs.createReadStream(pathname.substr(1));
readerStream.setEncoding('UTF8');
readerStream.on('data', function(chunk) {
response.writeHead(200, {'Content-type': 'text/html'});
response.write(chunk);
console.log('Page is being streamed...');
});
readerStream.on('end', function() {
console.log('Page is streamed and emitted successfully.');
});
readerStream.on('error', function(err) {
response.writeHead(404, {'Content-type': 'text/html'});
console.log('Page streaming error: ' + err);
});
console.log('Code ends!');
}).listen(8081);
console.log('Server running at http://127.0.0.1:8081/');
我的
.html
.txt
文件包含三行短文本。启动服务器后,我通过
http://127.0.0.1:8081/index.html
. 一切正常
index.html
Node.js服务器正常吗?图标是否一直在转动,但对服务器没有任何成本?或者我错过了什么,图标不应该继续转动?