Repository navigation
Compatibility with other servers
Stack's primary focus is Node's core "http" module. However, due to it's simplicity, Stack ends up being compatible with any EventEmitter in Node that ends up firing an event with the standard request/response signature (usually a "request" event):
function(request, response) {}
Usually, to use Stack with another kind of server, all that is required is to overwrite the Stack.errorHandler function with one appropriate to your Server's API:
Stack.errorHandler = function(req, res, err) {
// Do your thing...
}
Note that overwriting the default errorHandler should be done before creating any Stacks (calling Stack()).
An example of another type of server that is compatible with Stack is TooTallNate's MODBUS module, which can be used to implement a client or server adhering to the MODBUS protocol.
Stack ends up working well for implementing the Server-side:
var Stack = require('stack');
var FC = require('modbus-stack').FUNCTION_CODES;
// Overwrite the default `Stack.errorHandler`
Stack.errorHandler = function (request, response, err) {
var errCode = err && err.errno ? err.errno : 1;
response.writeException(errCode);
}
require('modbus-stack/server').createServer(
Stack(
// Handle "Read Coils" (just call `next()` in this case..)
functionCode(FC.READ_COILS, function(req, res, next) {
next();
}),
// Handle "Read Input Registers"
functionCode(FC.READ_INPUT_REGISTERS, function(req, res, next) {
var resp = new Array(req.quantity);
for (var i=0; i < req.quantity; i++) {
resp[i] = req.startAddress + i;
}
res.writeResponse(resp);
})
)
).listen(502);
function functionCode(fc, callback) {
return function(req, res, next) {
req.functionCode === fc ?
callback.apply(this, arguments) :
next();
}
}