Skip to content

Instantly share code, notes, and snippets.

@nikkaroraa
Last active June 12, 2017 05:13
Show Gist options
  • Save nikkaroraa/01a5afb6ff035a8b92a4e946d3e881ec to your computer and use it in GitHub Desktop.
Save nikkaroraa/01a5afb6ff035a8b92a4e946d3e881ec to your computer and use it in GitHub Desktop.
app.use(express.static(path.join(__dirname, 'b')));
Right, app.use() loads a function to be used as middleware. In this context, it loads the result of express.static(path.join(__dirname, 'public')).
The result of express.static(path.join(__dirname, 'public')) is a function (in JavaScript, functions may return functions), a function that express understands as a middleware (i.e. it has the following signature: function(request, response, next) {
express.static() is a function that takes a path, and returns a middleware that serves all files in that path to /. (If you wanted to prefix it with /public or whatever, you'd write app.use('/public', express.static(path.join(__dirname, 'public'))), where the first /public is the web path and the second is the filesystem path of the files being served).
For better clarity, the following:
app.use('/a', express.static(path.join(__dirname, 'b')));
would serve all files inside of the b directory, and have them accessible through http://example.com/a/FILE.
......./node/b
--node
--b
--index.html
--javascript.js
the writeHead() is called to write the header of the response, that the application will serve to the client. The end() method both sends the content of the response to the client and signals to the server that the response (header and content) has been sent completely. If you are still going to send anything else, you should call write() method of res response object instead.
In short; body-parser extracts the entire body portion of an incoming request stream and exposes it on req.body as something easier to interface with. You don't need it per se, because you could do all of that yourself. However, it will most likely do what you want and save you the trouble.
path.join will take care of unneccessary delimiters, that may occur if the given pathes come from unknown sources (eg. user input, 3rd party APIs etc.).
So path.join('a/','b') path.join('a/','/b'), path.join('a','b') and path.join('a','/b') will all give a/b.
Without using it, you usually would make expectations about the start and end of the pathes joined, knowing they only have no or one slash.
The action attribute specifies where to send the form-data when a form is submitted.
res.send() will sends the HTTP response. Its syntax is,
res.send([body])
The body parameter can be a Buffer object, a String, an object, or an Array. For example:
res.send(new Buffer('whoop'));
res.send({ some: 'json' });
res.send('<p>some html</p>');
res.status(404).send('Sorry, we cannot find that!');
res.status(500).send({ error: 'something blew up' });
See this for more info.
res.end() will ends the response process. This method actually comes from Node core, specifically the response.end() method of http.ServerResponse. Use to quickly end the response without any data. Example:
res.end();
res.status(404).end();
I was trying to send huge text data(295mb) over http using res.send(data) and res.write(data). I noticed that res.send(data) is slower than res.write(data). I observed following things.
res.send(data): it can be called only once and it sends data in chunk of some buffer size to client and then again comes back and sends another chunk of buffer size so there is a lot of back and forth http communication.
res.write(data): It can be called multiple times followed by res.end() and It creates buffer size based on whole data and sends over http so it would be faster in case of huge amount of data.
The answer to your question is no. You don't have to call res.end() if you call res.send(). res.send() calls res.end() for you.
Taken from /lib/response.js, here is the end of the res.send() function:
//. . .
// respond
this.end(head ? null : body);
return this;
}
Buffers in Node.js
JavaScript works on Unicode and not on the binary data. Therefore, when we are dealing with TCP streams for files, it is necessary to handle octet streams. Node.js provides the Buffer class that provides instances with which we can store raw data in the similar way when we deal with arrays. But here the raw data storage corresponds to a raw memory allocation which is outside the V8 heap.
Refer: https://www.eduonix.com/blog/web-programming-tutorials/learn-concept-buffers-node-js/
body-parser extract the entire body portion of an incoming request stream and exposes it on req.body as something easier to interface with . Yeah ! you can do it by yourself as well but using body-parser will do what is required and will save your trouble.
Now , that was just the summary ; in depth , body-parser gives you a middleware which uses nodejs/zlib to unzip incoming request data if its zipped and stream-utils/raw-body to await full raw content of the request body before "parsing it".
After having the raw contents , body-parser will parse it using one of the four strategies , depending on specific middleware you decided to use :
bodyParser.raw() : Does not actually parse the body , but just exposes the buffered up contents from before in a buffer on req.body .
bodyParser.text() : Reads the buffer as plain text and exposes the resulting string on req.body.
bodyParser.urlencoded() : Parses the text as URL encoded data (which is how browsers tend to send form data from regular forms set to POST) and exposes the resulting object (containing the keys and values) on req.body. For comparison; in PHP all of this is automatically done and exposed in $_POST.
bodyParser.json() : Parses the text as JSON and exposes the resulting object on req.body.
Only after setting the req.body to the desirable contents will it call the next middleware in the stack, which can then access the request data without having to think about how to unzip and parse it.
When you submit form data with a POST request, that form data can be encoded in many ways. The default type for HTML forms is application/x-www-urlencoded, but you can also submit data as JSON or any other arbitrary format.
bodyParser.urlencoded() provides middleware for automatically parsing forms with the content-type application/x-www-urlencoded and storing the result as a dictionary (object) in req.body. The body-parser module also provides middleware for parsing JSON, plain text, or just returning a raw Buffer object for you to deal with as needed.
A new body object containing the parsed data is populated on the request object after the middleware (i.e. req.body). This object will contain key-value pairs, where the value can be a string or array (when extended is false), or any type (when extended is true).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment