Nodeproxy

nodeproxy – npm

nodeproxy1. 0. 0 • Public • Published 9 years ago Readme Explore BETA0 Dependencies6 Dependents1 Versions
A port of the jQuery proxy functionality to NodeJS.
Installation
The easiest way to install is through the Node Package Manager (NPM):
npm install nodeproxyUsage
var nodeproxy = require(‘nodeproxy’);function ObjectOne(){ function helloWorld(){ (“Hello ” +);} return { helloWorld: helloWorld}}function ObjectTwo(){ function init(){ var contextObject = { name: ‘iain’}; var objectOne = new ObjectOne(); nodeproxy(objectOne. helloWorld, contextObject)();} return { init: init}}var objectTwo = new ObjectTwo();();
NodeProxy | SuperCollider 3.11.2 Help

NodeProxy | SuperCollider 3.11.2 Help

Description
Generally a proxy is a placeholder for something. A node proxy is a placeholder for something playing on a server and writes to a limited number of busses (usually a synth, but also an event stream that makes synths). NodeProxy objects can be replaced and recombined while they play. Also they can be used to build a larger structure which is used and modified later on. Overview: JITLib.
NodeProxy is used internally in ProxySpace and it is a superclass of Ndef, allowing to easily access and combine a large number of placeholders.
Graphical editor for a node proxy: NodeProxy plays on a private bus. If you want to hear the output, use -play and -stop. To free inner players and stop listen: -end. Entirely removing all inner settings: -clearFurther reading
the_lazy_proxyjitlib_efficiencyjitlib_fadingjitlib_asCompileStringNodeProxy roles
First Example
Class Methods
Creation
(server, rate, numChannels, inputs)
Return a new instance of NodeProxy.
Arguments:
server
The server on which to run and where the bus is allocated (default: fault)rate
If given, proxy is initialized to this ratenumChannels
If given, proxy is initialized to this number of channelsinputs
If given, proxy is initialized with the given inputs as objects on subsequent (server, numChannels)
Create a new audio rate instance on the given ntrol(server, numChannels)
Create a new audio rate instance on the given (bus)
Create an instance with a given cessing Class Variables
faultNumAudio
faultNumAudio = value
Default number of channels when initializing in audio rate and no specific number is given (default: 2)faultNumControl
faultNumControl = value
Default number of channels when initializing in control rate and no specific number is given (default: 1)faultFadeTime
The overlap time between successive source replacements which all instances have by default. Each instance has its own value which can be set via herited class methods
Instance Methods
Listening to the output
(out, numChannels, group, multi: false, vol, fadeTime, addAction)
Play from a bus index with a number of channels to another index with a number of channels, within a Group (i. e. a target group or server). Arguments:
out
bus indexnumChannels
number of channels to output. If BusPlug is neutral or reshaping is elastic, initialize it to this number. If this is more than the available channels, wrap around. If this is not given, and reshaping is elastic, it will automatically
target Group or Server in which to play the monitor
keep old playback links and add new onevol
overall volume at which to monitorfadeTime
fade in / fade out timeaddAction
Where in the node tree to play the monitor (outs, amps, ins, vol, fadeTime, group, addAction)
Play back on non-contiguous channels. See: Monitor and playNArguments:
outs
array of destination channels (or single value)amps
array of amplitudes for each channel (or single value)ins
array of source channel offsets within the bus (or single value)vol
Overall volume (multiplied by amps)fadeTime
array of fadeTimes (or single value) for fade in / fade outgroup
target Group or Server in which to play the monitor dAction
Where in the node tree to play the monitor (fadeTime, reset: false)
stop to play out public guments:
fadeTime
decay time for this actionreset
if set to true, reset all monitor state. Otherwise, the previous play arguments are (fadeTime, reset: false)
releases the synths and stops guments:
cross fade time for this
if set to true, reset all monitor state. Otherwise, the previous play arguments are kept. Embedding and Combining the proxy
(numChannels, offset: 0, clip: ‘wrap’)
Return a link to numChannels of my output. If uninitialized, creates a matching bus. Normally, ar defaults to stereo, kr to mono. This can be set in the classvars: *defaultNumAudio, *defaultNumControl
For consistency, it always returns an array of signals when no numChannels are given. To make it a single ugen output, use cumChannels = 1. See also: guments:
numChannels
Number of channels returned. If the receiver is neutral or reshaping is elastic, initialize it to this number. If this is more than the available channels, use the clip behaviour (below). If set to 1, it will return an instance of InBus, otherwise an Array of one or more instances of
Channel offset when reading a bus that has more channels than numChannels, cross fading between adjacent
If set to ‘wrap’, exceeding channels will wrap around, if set to ‘clip’, repeat the last one. <--(proxy) Usage: proxyA <-- proxyB. Set proxyA source to proxyB and play proxyA. If proxyB was playing, fade it out. This is convenient in the following situation: <<>(proxy, key: ‘in’)
Chaining. Usage: proxyA <<> proxyB <<> proxyC <<>…. Map proxyC source to proxyB \in argument, and proxyB to proxyA’s in argument.
<>>(proxy, key: ‘in’)
Inverse of the above. Usage: proxyA <>> proxyB <>> proxyC <>>…. Setting the source
NodeProxy keeps a number of slots which can be sources and are mixed on the same bus.. The default source is the slot 0. All objects can be exchanged while running, and also before and after. Normally, the source is active immediately. If sources are to be exchanged “quietly”, set the node proxy to sleep (awake = false), or use the message prime().
See the list under section Supported
= obj
Play a new synth through proxy and release/remove any old ones.
obj
can be one of the supported inputs (see Supported sources)NOTE: When reshaping is set, e. g. to \elastic, setting the source can change the number of channels of the proxy. This means that its bus changes, and that child proxies, which read signals from it, may also change. See the example in uting
Signals can be routed between any number of node proxies.
See also: BusPlug: ar, BusPlug: value, reshaping.
Here is a simple example, using Ndef (NodeProxy works similarly):
NOTE: If you don’t specify the number of channels, an expression like (\maus) will return an Array. Subsequently, e. by a Pan2 UGen, you may get the message:
WARNING: Synth output should be a flat array.
If you intend the output to be really mono, make it explicit by writing: (\maus, 1)
With elastic reshaping, you can use the parent to expand the child, if you omit the number of channels in the routing:
Reserved parameters
Three parameters are automatically specified if they don’t exist in a given UGen function. You can override their use: [\out, \gate, \fadeTime]Specifying your own envelope
If a UGen function that is passed to the proxy has its own envelope, and if this envelope can free the synth, the node proxy uses this envelope instead of making its own. If you provide a fadeTime argument, the proxy’s fadeTime will be used.
Making copies
copies the hidden internal state to make the new proxy independent of the old, but will keep the reference to the source object. The rendered SynthDef is cached, which makes this method more efficient than simply assigning the same function to a new proxy. By design, the monitor is copied, but is not running (use play to start it in the same configuration).
NOTE: If needed, you can also copy parts of a proxy, such as the Monitor (which usually routes the output back onto hardware busses) and the NodeMap, which keeps a mapping and setting pyState(proxy)
Copy the internal settings of one proxy into another. Old state is guments:
proxy
The proxy whose internal state is shaping. reshaping. reshaping = value
Determines how to behave when a new source is added. Current options:
nilOnce initialized, keep the same bus – this is the default\elasticOn a change, shrink and grow according to need, replace bus. The monitor and child proxies are adjusted. \expandingOn a change, only grow according to need, replace bus. The monitor and child proxies are adjusted.
(numChannels, rate, argReshaping, fadeTime)
Adjust the proxy to a given rate / numChannels. If there are any child proxies that have elastic -reshaping, they are adjusted accordingly.
Other ways to set or change the sources
(obj)
Set source without starting the synth. To start it, -send can be used later. Running synths are released and proxy is initialized if still (obj, channelOffset: 0, extraArgs, now: true)
Add a new source to the present moveAt(index, fadeTime)
Remove the object at index i and its synths, if they exist. If no index is supplied, remove them moveLast(fadeTime)
Remove the last object and its synths, if they (index, obj, channelOffset: 0, extraArgs, now: true)
Set the source by index. Objects can be inserted at any index, only the order of indices is relevant. Internally, NodeProxy uses an Order to access the guments:
index
where the object should be placed in the internal order. if -1, all objects are freedobj
A valid source (see Supported sources). channelOffset
using a multichannel setup it can be useful to set this, when the objects numChannels is smaller than the proxyextraArgs
Arguments that can be sent with the object directly (not cached)now
if set to false, only prepare the source and do not start the object (see -prime)
Controlling the running processes
Pause all objects and set proxy to
If paused, start all build
Rebuild all SynthDefs from sources.. orderNodes(… proxies)
Arrange the order of groups from this to the last. This can be important when external input is filtered in order to minimize latency. Note that if a -parentGroup was provided, the nodes must be in the same lease and cleaning up
(fadeTime, freeGroup: true)
Release all running synths and the group. If patterns are playing, stop guments:
decay time for this actionfreeGroup
a lease(fadeTime)
release running synths. If patterns are playing, stop guments:
decay time for this (fadeTime: 0)
reset everything to nil, neutralizes rate/numChannelsArguments:
if a fadeTime is given, first fade out, then hedAfterFade(func)
Calls a function after the fadeTime and server latency have passed. If the proxy specifies a quant value, the function is evaluated fadeTime + latency seconds after the next timepoint on the quant grid; otherwise, the fade delay begins guments:
func
a function to be called at the appropriate timeAccessing Instance Variables. sources. sources = list
Returns an array of all
Returns the first
The node proxy’s server (a Server).
= inBus
The node proxy’s private bus (a Bus). Because it has a private bus, it is not audible directly – monitoring it by ( or playN) routes it to the hardware output
The bus rate (default: nil) The rate and number of channels is determined either when the instance is created (. control/) or by lazy initialisation from the first source (see the_lazy_proxy). numChannels
The bus numChannels (default: nil). isNeutral
true if the proxy has no initialized
= inGroup
The node proxy’s group (a Group). This is maintained by the proxy and serves as a context in which all synths are rentGroup. parentGroup = node
Access the parentGroup (default: nil), which can be set to run the proxy’s group in another group. This group has to be maintained (kept playing etc. )
= value
A clock, which can be set to account for different timing schemes, such as beat accurate replacement of
A quant value, to specify quantizes replacement of sources. Compatible with the general use of quant in SuperCollider.. quantize(… proxies)
Synchronize the proxies by resending and adjusting to nitor. monitor = value
Access the Monitor object, which plays back the output of the proxy’s private
Returns true if the object has been initialized on the server, e. a synthDef has been
Returns true if the processes are
If set to false (default: true), a change of the source does not start a new synth immediately. This is useful when synths are triggered by -spawn, and a change of sound should not duplicate sends.. fadeTime. fadeTime = dur
Setting synth controls
(… args)
NodeProxy behaves like its NodeMap and very similar to a Now the methods map, setn, mapn, and xmap are there just for backward compatibility reasons. Everything is done by guments:… args
An array of pairs: key, value, key, value,…
The unique key (a Symbol) specifies the control name to be set.
For value anything can be specified that responds to “asControlInput”, in particular:
numberset the control to that numberarray of numbersset the subsequent control channels to the corresponding valuenode proxymap subsequent control channels to the corresponding proxy output channel
(… keys)
Remove specified settings and unmap or unset the (… args)
set/map with a crossfade into the new setting. The crossfadeT time is the NodeProxy (… args)
set the lag values of these args (identical to -setRates). To remove these settings, use: lag(\key1, nil, key2, nil,… ). setRates(… args)
set the default rate (\tr, \ir, numerical) for synthDef arg. A rate of nil removes ntrolNames(except, addNodeMap: true)
Returns the ControlName objects of all slots, except the names of this list (default: [\out, \i_out, \gate, \fadeTime], which are used internally)ntrolKeys(except, noInternalKeys: true)
Returns the keys (symbols) of all control names objects of all slots, except the names of this list. (default: none). Arguments:
except
list of namesnoInternalKeys
If noInternalKeys is true (default: true), it ignores the keys [\out, \i_out, \gate, \fadeTime] tKeysValues(keys, except, withDefaults: true, noInternalKeys: true)
Get all key value pairs from both NodeMap (the settings) and default ntrolKeysValues(keys, except)
Get all key value pairs from default
Get the specs array from SynthDef metadata. Note that, for a NodeProxy with multiple sources, result will be a dictionary containing specs of ALL source SynthDefs.
Sending synths to server explicitly
Normally, processes (usually synths) are started when their respective source is added to the proxy. The processes can also be restarted, however, or the proxy can be used while asleep and the processes can then be started (extraArgs, index, freeLast: true)
Send a new synth without releasing the old one. If the source is a stream or a pattern, it starts a new guments:
extraArgs
Arguments used to set the synth. The argument list is applied to the synth only. Arguments specified here override settings in the node map, but leave them
What slot to send a new synth with. If nil, uses all. (default: nil)freeLast
if to free the last synth at that index or not (default: true). sendAll(extraArgs, freeLast: true)
Send all synths, or restart all guments:
Arguments used to set the synth. the argument list is applied to the synth eeLast
if to free the last synth at that index or not (default: true). sendEach(extraArgs, freeLast: true)
Like send, just iterating separately over the
Until the proxy is not used by any output ( either or) it is not running on the server. you can wake it up to force it playing. Normally this is not oring as code
(includeSettings: true, includeMonitor: true, envir)
stores the proxy as executable code. see also jitlib_asCompileString for more examples.
Inherited instance methods
Undocumented instance methods. addChild(proxy). addNodeMapControlNames(objCtlNames, except: []). asGroup. asNodeID. asTarget
(index). children. cleanNodeMap. deepWakeUp. defaultGroupID. document(includeSettings: true, includeMonitor: true)
(nSliders, parent, bounds)
(i, func). findInOpenDocuments(index: 0). freeBus
(param). getBundle. getDefaultVal(key). getFamily(set, alreadyAsked). getStructure(alreadyAsked)
(numItems, bounds, preset). internalKeys. isPlaying
(envir). loadToBundle(bundle). mapEnvir(… keys). moveBeforeMsg(… proxies). nameDef(name, index: 0). nodeMap. nodeMap = map. nudgeSet(param, incr: 0. 02, spec). nudgeVol(incr: 0. objects. playEditString(usePlayN, dropDefaults: false, nameStr). playNDialog(bounds, usePlayN). playNString(dropDefaults: false). playString(dropDefaults: false). prepareOtherObjects(bundle, index, busChanged). prepareToBundle(argGroup, bundle, addAction: ‘addToTail’)
(list, index: 0, channelOffset: 0). putNewObject(bundle, index, container, extraArgs, now). putSeries(first, second, last, value)
(proxies). readFromBus(busses). reallocBusIfNeeded. rebuildDeepToBundle(bundle, busWasChangedExternally: true, checkedAlready, timeArgs). rebuildToBundle(bundle, timeArgs). removeAll(fadeTime). removeAllToBundle(bundle, fadeTime). removeChild(proxy). removeFirst(fadeTime). removeToBundle(bundle, index, fadeTime). resetNodeMap. sendAllToBundle(bundle, extraArgs). sendEachToBundle(bundle, extraArgs). sendObjectToBundle(bundle, object, extraArgs, index). servStr. serverQuit
(argBus). setGroup(args, useLatency: false). setNodeMap(map, xfade: true). shouldAddObject(obj). softSet(param, val, within: 0. 025, mapped: true, lastVal, spec). softVol_(val, within: 0. 025, pause: true, lastVal, spec)
(extraArgs, index: 0). stopAllToBundle(bundle, fadeTime). supplementNodeMap(keys, replaceOldKeys: false)
(index: 0). typeStr. unsetToBundle(bundle, keys). wakeUpParentsToBundle(bundle, checkedAlready). wakeUpToBundle(bundle, checkedAlready). xFadePerform(selector, args)
Examples
For more, see ProxySpace
Supported sources
NodeProxyplayed by reading from the other NodeProxy ctioninterpreted as ugen function, and plays a Synth, similar to this value to the bus continuously, overwriting previous bus of numberswrite the values to the bus continuously overwriting previous bus value. Busread the signal on the nthDefplays a Synth using the mbolplays a Synth from the SynthDef with this tternplayed as event pattern (using Pbind or other event patterns). Streamplayed as event stream (a stream returning events) removes all, EventPatternProxyplayed like a stream. Taskplayed, no output is efplayed like TaskEventplayed like in a sociations (NodeProxy roles):
(\filter -> func)filter previous input (with post control)(\filterIn -> func)filter previous input (with pre control)(\set -> event pattern)set controls with the event keys of the pattern(\setbus -> event pattern)set bus with an event pattern. Bus value is the \value key of each event. (\setsrc -> event pattern)set the source with an event pattern. source is the \source key of event. (\control -> array or number)prepare an efficient way to set values by index(\mix -> func)mix audio
crucial library:
AbstractPlayerstarted in a separate bus, mapped to this busInstrconverted to player and started
Definitions for other sources can be added – see: NodeProxy roles
A full-featured http proxy for node.js - GitHub

A full-featured http proxy for node.js – GitHub

node–proxy is an HTTP programmable proxying library that supports
websockets. It is suitable for implementing components such as reverse
proxies and load balancers.
Table of Contents
Installation
Upgrading from 0. 8. x?
Core Concept
Use Cases
Setup a basic stand-alone proxy server
Setup a stand-alone proxy server with custom server logic
Setup a stand-alone proxy server with proxy request header re-writing
Modify a response from a proxied server
Setup a stand-alone proxy server with latency
Using HTTPS
Proxying WebSockets
Options
Listening for proxy events
Shutdown
Miscellaneous
Test
ProxyTable API
Logo
Contributing and Issues
License
npm install -proxy –save
Back to top
Click here
A new proxy is created by calling createProxyServer and passing
an options object as argument (valid properties are available here)
var Proxy = require(‘-proxy’);
var proxy = eateProxyServer(options); // See (†)
†Unless listen(.. ) is invoked on the object, this does not create a webserver. See below.
An object will be returned with four methods:
web req, res, [options] (used for proxying regular HTTP(S) requests)
ws req, socket, head, [options] (used for proxying WS(S) requests)
listen port (a function that wraps the object in a webserver, for your convenience)
close [callback] (a function that closes the inner webserver and stops listening on given port)
It is then possible to proxy requests by calling these functions
eateServer(function(req, res) {
(req, res, { target: ”});});
Errors can be listened on either using the Event Emitter API
(‘error’, function(e) {… });
or using the callback API
(req, res, { target: ”}, function(e) {… });
When a request is proxied it follows two different pipelines (available here)
which apply transformations to both the req and res object.
The first pipeline (incoming) is responsible for the creation and manipulation of the stream that connects your client to the target.
The second pipeline (outgoing) is responsible for the creation and manipulation of the stream that, from your target, returns data
to the client.
var = require(”),
Proxy = require(‘-proxy’);
//
// Create your proxy server and set the target in the options.
eateProxyServer({target:’localhost:9000′})(8000); // See (†)
// Create your target server
eateServer(function (req, res) {
res. writeHead(200, { ‘Content-Type’: ‘text/plain’});
(‘request successfully proxied! ‘ + ‘\n’ + ringify(req. headers, true, 2));
();})(9000);
†Invoking listen(.. ) triggers the creation of a web server. Otherwise, just the proxy instance is created.
This example shows how you can proxy a request using your own HTTP server
and also you can put your own logic to handle the request.
// Create a proxy server with custom application logic
var proxy = eateProxyServer({});
// Create your custom server and just call `()` to proxy
// a web request to the target passed in the options
// also you can use `()` to proxy a websockets request
var server = eateServer(function(req, res) {
// You can define here your custom logic to handle the request
// and then proxy the request.
(“listening on port 5050″)
(5050);
This example shows how you can proxy a request using your own HTTP server that
modifies the outgoing proxy request by adding a special header.
// To modify the proxy connection before data is sent, you can listen
// for the ‘proxyReq’ event. When the event is fired, you will receive
// the following arguments:
// (ientRequest proxyReq, comingMessage req,
// rverResponse res, Object options). This mechanism is useful when
// you need to modify the proxy request before the proxy connection
// is made to the target.
(‘proxyReq’, function(proxyReq, req, res, options) {
tHeader(‘X-Special-Proxy-Header’, ‘foobar’);});
(req, res, {
target: ”});});
Sometimes when you have received a HTML/XML document from the server of origin you would like to modify it before forwarding it on.
Harmon allows you to do this in a streaming style so as to keep the pressure on the proxy to a minimum.
// Create a proxy server with latency
var proxy = eateProxyServer();
// Create your server that makes an operation that waits a while
// and then proxies the request
// This simulates an operation that takes 500ms to execute
setTimeout(function () {
target: ‘localhost:9008’});}, 500);})(8008);
(‘request successfully proxied to: ‘ + + ‘\n’ + ringify(req. headers, true, 2));
();})(9008);
You can activate the validation of a secure SSL certificate to the target connection (avoid self-signed certs), just set secure: true in the options.
HTTPS -> HTTP
// Create the HTTPS proxy server in front of a HTTP server
eateServer({
target: {
host: ‘localhost’,
port: 9009},
ssl: {
key: adFileSync(”, ‘utf8’),
cert: adFileSync(”, ‘utf8’)}})(8009);
HTTPS -> HTTPS
// Create the proxy server listening on port 443
cert: adFileSync(”, ‘utf8’)},
target: ‘localhost:9010’,
secure: true // Depends on your needs, could be false. })(443);
HTTP -> HTTPS (using a PKCS12 client certificate)
// Create an HTTP proxy server with an HTTPS target
eateProxyServer({
protocol: ‘:’,
host: ‘my-domain-name’,
port: 443,
pfx: adFileSync(‘path/to/certificate. p12’),
passphrase: ‘password’, },
changeOrigin: true, })(8000);
You can activate the websocket support for the proxy using ws:true in the options.
// Create a proxy server for websockets
target: ‘wslocalhost:9014’,
ws: true})(8014);
Also you can proxy the websocket requests just calling the ws(req, socket, head) method.
// Setup our server to proxy standard HTTP requests
var proxy = new eateProxyServer({
port: 9015}});
var proxyServer = eateServer(function (req, res) {
(req, res);});
// Listen to the `upgrade` event and proxy the
// WebSocket requests as well.
(‘upgrade’, function (req, socket, head) {
(req, socket, head);});
(8015);
eateProxyServer supports the following options:
target: url string to be parsed with the url module
forward: url string to be parsed with the url module
agent: object to be passed to (s). request (see Node’s agent and agent objects)
ssl: object to be passed to eateServer()
ws: true/false, if you want to proxy websockets
xfwd: true/false, adds x-forward headers
secure: true/false, if you want to verify the SSL Certs
toProxy: true/false, passes the absolute URL as the path (useful for proxying to proxies)
prependPath: true/false, Default: true – specify whether you want to prepend the target’s path to the proxy path
ignorePath: true/false, Default: false – specify whether you want to ignore the proxy path of the incoming request (note: you will have to append / manually if required).
localAddress: Local interface string to bind for outgoing connections
changeOrigin: true/false, Default: false – changes the origin of the host header to the target URL
preserveHeaderKeyCase: true/false, Default: false – specify whether you want to keep letter case of response header key
auth: Basic authentication i. e. ‘user:password’ to compute an Authorization header.
hostRewrite: rewrites the location hostname on (201/301/302/307/308) redirects.
autoRewrite: rewrites the location host/port on (201/301/302/307/308) redirects based on requested host/port. Default: false.
protocolRewrite: rewrites the location protocol on (201/301/302/307/308) redirects to ” or ”. Default: null.
cookieDomainRewrite: rewrites domain of set-cookie headers. Possible values:
false (default): disable cookie rewriting
String: new domain, for example cookieDomainRewrite: “”. To remove the domain, use cookieDomainRewrite: “”.
Object: mapping of domains to new domains, use “*” to match all domains.
For example keep one domain unchanged, rewrite one domain and remove other domains:
cookieDomainRewrite: {
“”: “”,
“*”: “”}
cookiePathRewrite: rewrites path of set-cookie headers. Possible values:
String: new path, for example cookiePathRewrite: “/newPath/”. To remove the path, use cookiePathRewrite: “”. To set path to root use cookiePathRewrite: “/”.
Object: mapping of paths to new paths, use “*” to match all paths.
For example, to keep one path unchanged, rewrite one path and remove other paths:
cookiePathRewrite: {
“/”: “/”,
headers: object with extra headers to be added to target requests.
proxyTimeout: timeout (in millis) for outgoing proxy requests
timeout: timeout (in millis) for incoming requests
followRedirects: true/false, Default: false – specify whether you want to follow redirects
selfHandleResponse true/false, if set to true, none of the webOutgoing passes are called and it’s your responsibility to appropriately return the response by listening and acting on the proxyRes event
buffer: stream of data to send as the request body. Maybe you have some middleware that consumes the request stream before proxying it on e. g. If you read the body of a request into a field called ‘req. rawbody’ you could restream this field in the buffer option:
‘use strict’;
const streamify = require(‘stream-array’);
const HttpProxy = require(‘-proxy’);
const proxy = new HttpProxy();
module. exports = (req, res, next) => {
target: ‘localhost:4003/’,
buffer: streamify(req. rawBody)}, next);};
NOTE:
and are optional.
and rward cannot both be missing
If you are using the method, the following options are also applicable:
error: The error event is emitted if the request to the target fail. We do not do any error handling of messages passed between client and proxy, and messages passed between proxy and target, so it is recommended that you listen on errors and handle them.
proxyReq: This event is emitted before the data is sent. It gives you a chance to alter the proxyReq request object. Applies to “web” connections
proxyReqWs: This event is emitted before the data is sent. Applies to “websocket” connections
proxyRes: This event is emitted if the request to the target got a response.
open: This event is emitted once the proxy websocket was created and piped into the target websocket.
close: This event is emitted once the proxy websocket was closed.
(DEPRECATED) proxySocket: Deprecated in favor of open.
// Error example
// Http Proxy Server with bad target
var proxy = eateServer({
target:’localhost:9005′});
(8005);
// Listen for the `error` event on `proxy`.
(‘error’, function (err, req, res) {
res. writeHead(500, {
‘Content-Type’: ‘text/plain’});
(‘Something went wrong. And we are reporting a custom error message. ‘);});
// Listen for the `proxyRes` event on `proxy`.
(‘proxyRes’, function (proxyRes, req, res) {
(‘RAW Response from the target’, ringify(proxyRes. headers, true, 2));});
// Listen for the `open` event on `proxy`.
(‘open’, function (proxySocket) {
// listen for messages coming FROM the target here
(‘data’, hybiParseAndLogMessage);});
// Listen for the `close` event on `proxy`.
(‘close’, function (res, socket, head) {
// view disconnected websocket connections
(‘Client disconnected’);});
When testing or running server within another program it may be necessary to close the proxy.
This will stop the proxy from accepting new connections.
port: 1337}});
();
If you want to handle your own response after receiving the proxyRes, you can do
so with selfHandleResponse. As you can see below, if you use this option, you
are able to intercept and read the proxyRes but you must also make sure to
reply to the res itself otherwise the original client will never receive any
data.
Modify response
var option = {
target: target,
selfHandleResponse: true};
var body = [];
(‘data’, function (chunk) {
(chunk);});
(‘end’, function () {
body = (body). toString();
(“res from proxied server:”, body);
(“my response to cli”);});});
(req, res, option);
A proxy table API is available through this add-on module, which lets you define a set of rules to translate matching routes to target routes that the reverse proxy will talk to.
Logo created by Diego Pasquali
Read carefully our Code Of Conduct
Search on Google/Github
If you can’t find anything, open an issue
If you feel comfortable about fixing the issue, fork the repo
Commit to your local branch (which must be different from master)
Submit your Pull Request (be sure to include tests and update documentation)
The MIT License (MIT)
Copyright (c) 2010 – 2016 Charlie Robbins, Jarrett Cruger & 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.

Frequently Asked Questions about nodeproxy

Leave a Reply

Your email address will not be published. Required fields are marked *