综合技术

Why do we need buffers in node.js?

微信扫一扫,分享到朋友圈

Why do we need buffers in node.js?
0

To display the contents of the file in browser using node, I first tried this:

var express = require('express')
  , fs  = require('fs')
  , app = express()
  , port = process.env.PORT || 5000;

app.use(express.logger());

var data = fs.readFileSync('index.html');


app.get('/', function(req, res){
  res.send(data);
});

app.listen(port, function(){
  console.log('Listenting on ' + port);
});

However, this didn’t work as expected. Browser actually offered to contents of index.html
as file that I first have to download & then manually open that in text editor. then, I tried using buffer to do the same thing:

var express = require('express')
  , fs  = require('fs')
  , app = express()
  , port = process.env.PORT || 5000;

app.use(express.logger());

var data = new Buffer(fs.readFileSync('index.html'));


app.get('/', function(req, res){
  res.send(data.toString('utf-8'));
});

app.listen(port, function(){
  console.log('Listenting on ' + port);
});

This works as expected & contents of index.html
were display inside the browser window. However, In My limited userstanding about Node.js
. Buffer class is a global type for dealing with binary data. However the index.html
file didn’t contain any binary data. so my questions are:

index.html

Problem courtesy of: CuriousMind

Solution

The correct way to return a file would be to use an async method instead of a sync method.:

app.get('/', function(req, res){
   res.writeHead(200, {
    'Content-Type': 'text/plain' // set to whatever mime type you need. 
  });
  fileSystem.createReadStream(filePath).pipe(res);
});

If you’re going to serve static files with express then you should use the static middleware.

To find out the differences in your example, have a look at the content-type being returned. That’s what would determine what the browser does with your response.

In the first case, Express.js would have seen a Buffer and decided to return the data as content-type "application/octet-stream". Your browser would not know what to do with this and return it as a download file.

In the second case, Express.js would have seen a String and decided to return the data as content-type "text/plain". Your browser knows how to deal with that and would show it to you.

I don’t think your question has much to do with buffers in node.js
but more to do with how Express.js res.send handles various input types.

If you’re new to Node then you don’t need to know about Buffers right away I think. Otherwise have a look at the docs: http://nodejs.org/api/buffer.html#buffer_buffer

Solution courtesy of: AndyD

阅读原文...


微信扫一扫,分享到朋友圈

Why do we need buffers in node.js?
0

Node.js Recipes

Book Memo: “Markov Chains”

上一篇

What is WebAssembly?

下一篇

评论已经被关闭。

插入图片

热门分类

往期推荐

Why do we need buffers in node.js?

长按储存图像,分享给朋友