Research
Security News
Quasar RAT Disguised as an npm Package for Detecting Vulnerabilities in Ethereum Smart Contracts
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
A hybrid buffered / streaming middleware kernel backwards compatible with connect.
The 'union' npm package is a hybrid routing HTTP server with a powerful middleware ecosystem. It is designed to create custom Node.js HTTP servers by combining various middleware and routing logic. Union is particularly useful for building applications that require a high level of customization in their HTTP server behavior.
Custom Server Creation
This code sample demonstrates how to create a custom HTTP server using Union. The 'before' array allows you to add middleware functions that process requests before they reach your main logic.
const union = require('union');
const http = require('http');
const server = union.createServer({
before: [
function (req, res) {
res.emit('next');
}
]
});
server.listen(3000, function () {
console.log('Server running on port 3000');
});
Middleware Integration
This example shows how to integrate a routing library, 'director', as middleware in a Union server. The router's dispatch method is bound and used as middleware, allowing for route handling within the Union server.
const union = require('union');
const director = require('director');
const router = new director.http.Router();
const server = union.createServer({
before: [
function (req, res) {
res.emit('next');
},
router.dispatch.bind(router)
]
});
Express is a widely used web application framework for Node.js, designed for building web applications and APIs. It is more abstracted and less flexible in terms of raw HTTP handling compared to Union, but it offers a simpler, more feature-rich interface for common server tasks.
Connect is an extensible HTTP server framework for node using 'plugins' known as middleware, similar to Union. It is the foundation upon which Express was built. While Connect is more minimalistic compared to Union, it serves a similar purpose in allowing middleware to be chained for request handling.
Koa is a new web framework designed by the team behind Express, aiming to be a smaller, more expressive, and more robust foundation for web applications and APIs. Unlike Union, Koa uses a modern approach with generators and async/await to ditch callbacks and greatly increase error-handling capabilities.
A hybrid streaming middleware kernel backwards compatible with connect.
The advantage to streaming middlewares is that they do not require buffering the entire stream in order to execute their function.
There are a few ways to use union
. Install the library using npm. You can add it to your package.json
file as a dependancy
$ [sudo] npm install union
Union's request handling is connect-compatible, meaning that all existing connect middlewares should work out-of-the-box with union.
(Union 0.3.x is compatible with connect >= 2.1.0)
In addition, the response object passed to middlewares listens for a "next" event, which is equivalent to calling next()
. Flatiron middlewares are written in this manner, meaning they are not reverse-compatible with connect.
var fs = require('fs'),
union = require('../lib'),
director = require('director');
var router = new director.http.Router();
var server = union.createServer({
before: [
function (req, res) {
var found = router.dispatch(req, res);
if (!found) {
res.emit('next');
}
}
]
});
router.get(/foo/, function () {
this.res.writeHead(200, { 'Content-Type': 'text/plain' })
this.res.end('hello world\n');
});
router.post(/foo/, { stream: true }, function () {
var req = this.req,
res = this.res,
writeStream;
writeStream = fs.createWriteStream(Date.now() + '-foo.txt');
req.pipe(writeStream);
writeStream.on('close', function () {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('wrote to a stream!');
});
});
server.listen(9090);
console.log('union with director running on 9090');
To demonstrate the code, we use director. A light-weight, Client AND Server side URL-Router for Node.js and Single Page Apps!
Code based on connect
var connect = require('connect')
, http = require('http');
var app = connect()
.use(connect.favicon())
.use(connect.logger('dev'))
.use(connect.static('public'))
.use(connect.directory('public'))
.use(connect.cookieParser('my secret here'))
.use(connect.session())
.use(function (req, res) {
res.end('Hello from Connect!\n');
});
http.createServer(app).listen(3000);
Code based on union
var connect = require('connect')
, union = require('union');
var server = union.createServer({
buffer: false,
before: [
connect.favicon(),
connect.logger('dev'),
connect.static('public'),
connect.directory('public'),
connect.cookieParser('my secret here'),
connect.session(),
function (req, res) {
res.end('Hello from Connect!\n');
},
]
}).listen(3000);
The options
object is required. Options include:
Specification
function createServer(options)
@param options {Object}
An object literal that represents the configuration for the server.
@option before {Array}
The `before` value is an array of middlewares, which are used to route and serve incoming
requests. For instance, in the example, `favicon` is a middleware which handles requests
for `/favicon.ico`.
@option after {Array}
The `after` value is an array of functions that return stream filters,
which are applied after the request handlers in `options.before`.
Stream filters inherit from `union.ResponseStream`, which implements the
Node.js core streams api with a bunch of other goodies.
@option limit {Object}
(optional) A value, passed to internal instantiations of `union.BufferedStream`.
@option https {Object}
(optional) A value that specifies the certificate and key necessary to create an instance of
`https.Server`.
@option spdy {Object}
(optional) A value that specifies the certificate and key necessary to create an instance of
`spdy.Server`.
@option headers {Object}
(optional) An object representing a set of headers to set in every outgoing response
Example
var server = union.createServer({
before: [
favicon('./favicon.png'),
function (req, res) {
var found = router.dispatch(req, res);
if (!found) {
res.emit('next');
}
}
]
});
An example of the https
or spdy
option.
{
cert: 'path/to/cert.pem',
key: 'path/to/key.pem',
ca: 'path/to/ca.pem'
}
An example of the headers
option.
{
'x-powered-by': 'your-sweet-application v10.9.8'
}
Error handler is similiar to middlware but takes an extra argument for error at the beginning.
var handle = function (err, req, res) {
res.statusCode = err.status;
res.end(req.headers);
};
var server = union.createServer({
onError: handle,
before: [
favicon('./favicon.png'),
function (req, res) {
var found = router.dispatch(req, res);
if (!found) {
res.emit('next');
}
}
]
});
This constructor inherits from Stream
and can buffer data up to limit
bytes. It also implements pause
and resume
methods.
Specification
function BufferedStream(limit)
@param limit {Number}
the limit for which the stream can be buffered
Example
var bs = union.BufferedStream(n);
This constructor inherits from union.BufferedStream
and returns a stream with these extra properties:
Specification
function HttpStream()
Example
var hs = union.HttpStream();
The url from the request.
Example
httpStream.url = '';
The HTTP headers associated with the stream.
Example
httpStream.headers = '';
The HTTP method ("GET", "POST", etc).
Example
httpStream.method = 'POST';
The querystring associated with the stream (if applicable).
Example
httpStream.query = '';
This constructor inherits from union.HttpStream
, and is additionally writeable. Union supplies this constructor as a basic response stream middleware from which to inherit.
Specification
function ResponseStream()
Example
var rs = union.ResponseStream();
All tests are written with vows and should be run with npm:
$ npm test
(The MIT License)
Copyright (c) 2010-2012 Charlie Robbins & the Contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
FAQs
A hybrid buffered / streaming middleware kernel backwards compatible with connect.
We found that union demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 4 open source maintainers 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.
Research
Security News
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
Security News
Research
A supply chain attack on Rspack's npm packages injected cryptomining malware, potentially impacting thousands of developers.
Research
Security News
Socket researchers discovered a malware campaign on npm delivering the Skuld infostealer via typosquatted packages, exposing sensitive data.