Security News
Fluent Assertions Faces Backlash After Abandoning Open Source Licensing
Fluent Assertions is facing backlash after dropping the Apache license for a commercial model, leaving users blindsided and questioning contributor rights.
http-enhanced
Advanced tools
Drop-in replacement for Node.js standard `http` API with various helpers.
My wrappers library was a bit over the top.
This is meant to be thinner, just a few helpers for the very simple req
/
res
that Node.js's http
API provides.
If you don't call any of the methods, nothing changes. You'll just have some extra prototype methods lying around that never did anything.
At the command line from the npm registry:
npm install http-enhanced
Or from github:
npm install git://github.com/chbrown/http-enhanced.git
Or in your package.json
:
"dependencies" : {
"http-enhanced": "*",
...
}
Most often, you'll create a server like this:
var http = require('http');
http.createServer(function (req, res) {
// req (request) is an instance of http.IncomingMessage
var url = req.url;
// res (response) is an instance of http.ServerResponse
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('Hello, world!');
res.end();
}).listen(80);
A simple change will let you use some shortcuts:
var http = require('http-enhanced');
http.createServer(function (req, res) {
// save incoming data to req.data and wait until the request ends,
// or callback immediately (setImmediate) if it already has
req.readToEnd('utf8', function(err, data) {
var reversed = data.split('').reverse().join('');
// 1. set HTTP status code to 200,
// 2. the Content-Type header to 'application/json',
// 3. and stringify the given object, all in one go:
res.json({success: true, message: reversed});
});
}).listen(80);
encoding
String | null If specified, callback gets a String instead of a Buffer.callback
Function | null Call some function(err, data)
when the request ends.
Read the request into a buffer until the end
event is triggered, which will
trigger callback(Error || null, Buffer || null)
. This uses "new-style"
streams, listening for readable
events and calling read()
, coercing to a
Buffer when needed.
This function can be called multiple times, with or without the callback.
A popular use case might be if you want to upload a file and do a lot of I/O
independently but at the same time. You might call req.readToEnd()
with no
arguments at the beginning of your request handler, and then set off your
expensive I/O calls.
You can get back a string if you specify the encoding, e.g.,
req.readToEnd('utf8', function(err, string) { ... })
. This is exactly
equivalent to calling:
req.readToEnd(function(err, buffer) {
var string = buffer.toString(encoding);
...
});
If the request has already ended, any captured buffer will be immediately
returned, via setImmediate
(which replaced process.nextTick
in node v0.10).
This might occur if you start listening for data
at some point, in which
case the request is flipped to "old-style" streams, and end
might occur
before you listen for it.
For that reason, and that calling req.read()
from multiple listeners could
produce problems, you should not use either of these:
req.setEncoding('utf8'); // no!
req.on('data', function(chunk) { ... }); // robot, NO!
So you shouldn't call req.readToEnd()
in your pipeline unless you're going
to call it again with a callback, later.
Wraps req.readToEnd()
and uses the request's Content-type
header to determine whether to parse the request as JSON or a form querystring.
JSON.parse
. Interprets empty application/json
requests as null
, instead of throwing (JSON.parse('')
will raise a SyntaxError normally).querystring.parse
.readToEnd
, a Buffer.Does not work for uploads (use something like formidable).
Returns the parsed querystring for GET requests.
data
String String to write to responseThe standard http
built-in response.end(data)
is supposed to write the
data and then end the response. From the docs:
If data is specified, it is equivalent to calling
request.write(data, encoding)
followed byrequest.end()
.
But sometimes it doesn't, and writeEnd
makes sure that's what it really does
(minus the optional encoding).
res.writeEnd('Hello world');
statusCode
Number Three-digit HTTP status codecontentType
String MIME typedata
String String to write to responseRoll writeHead(statusCode, contentType)
and writeEnd(data)
all into one:
res.writeAll(200, 'text/xml', '<root>Haha, not really.</root>');
object
Object JSON-stringifiable objectWrite response to end with Content-Type: application/json
and HTTP status
code 200, encoding the object with JSON.stringify
.
res.json({success: true, message: "Hello world!"});
If JSON.stringify
throws an error trying to encode your object (e.g., if it
has circular references), it will fall back to util.inspect
with the options:
{showHidden: true, depth: null}
.
data
String HTML to write to response.Set status code to 200 and Content-Type
to text/html
.
res.html('<p><i>Hello</i> world!.</p>');
data
String Plain text to write to response.Set status code to 200 and Content-Type
to text/plain
.
res.text('Hello world.');
statusCode
Number Optional three-digit HTTP status code. Defaults to 500.err
String | Error Will call err.toString()
.Set status code to given status code (or 500) and Content-Type
to
text/plain
.
res.die('Goodbye, cruel world.');
statusCode
Number Optional three-digit HTTP status code. Defaults to 302.location
String (a URL)Set status code to given status code (302 by default) and the Location
header to the given string. Also writes the text,
"Redirecting to: /index?error=404" (or whatever url you use).
res.redirect('/index?error=404');
Copyright © 2013–2014 Christopher Brown. MIT Licensed.
FAQs
Drop-in replacement for Node.js standard `http` API with various helpers.
The npm package http-enhanced receives a total of 15 weekly downloads. As such, http-enhanced popularity was classified as not popular.
We found that http-enhanced demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Fluent Assertions is facing backlash after dropping the Apache license for a commercial model, leaving users blindsided and questioning contributor rights.
Research
Security News
Socket researchers uncover the risks of a malicious Python package targeting Discord developers.
Security News
The UK is proposing a bold ban on ransomware payments by public entities to disrupt cybercrime, protect critical services, and lead global cybersecurity efforts.