Новичок в Node.js. Я понимаю, что функция createReadStream()
лучше для производительности, чем readFile()
, потому что createReadStream()
читает и записывает данные в патронах, а readFile()
сначала читает все содержимое. Таким образом, если файл большой, функция readFile()
может занять больше времени, прежде чем данные смогут быть обработаны дальше. Таким образом, я решил создать сервер, используя функцию createReadStream()
, как показано ниже.
// Create a server with fs.createReadStream(), better performance and less memory usage.
http.createServer( function (request, response) {
// Parse the request containing file name
var pathname = url.parse(request.url).pathname;
// Create a readable stream.
var readerStream = fs.createReadStream(pathname.substr(1));
// Set the encoding to be UTF8.
readerStream.setEncoding('UTF8');
// Handle stream events --> data, end and error
readerStream.on('data', function(chunk) {
// Page found
// HTTP Status: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-type': 'text/html'});
// Write the content of the file to response body.
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) {
// HTTP Status: 404 : NOT FOUND
// Content Type: text/plain
response.writeHead(404, {'Content-type': 'text/html'});
console.log('Page streaming error: ' + err);
});
console.log('Code ends!');
}).listen(8081);
// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');
Мой файл .html
или .txt
содержит три короткие строки текста. После запуска моего сервера я захожу на свою веб-страницу, перейдя по адресу http://127.0.0.1:8081/index.html
. Все работает нормально, и содержимое index.html
отображается в браузере.
Но на вкладке браузера иконка загрузчика все время крутится как будто держит загрузку около 1 минуты.
Это нормально для сервера Node.js? Значок просто продолжает вращаться, но ничего не стоит серверу? Или я что-то пропустил, и значок не должен постоянно вращаться?