SVR.JS API (.js mods)
SVR.JS has its API for .js mods that expands its functionality. SVR.JS API extends vanilla Node.JS HTTP API.
Error handling
When a JavaScript error is thrown outside of event callbacks, SVR.JS will return a 500 error to the client. Inside event callbacks, SVR.JS will simply crash.
Incorrect Error Handling:
//XXX WARNING!!! IT WILL CRASH THE SVR.JS!!!
//It also contains path traversal vulnerability!
module.exports = (req, res, logFacilities, config, next) => {
let headers = config.getCustomHeaders();
headers["Content-Type"] = "text/html; charset=utf8";
if (req.parsedURL.pathname == "/page.svr") {
fs.readFile(".template", (err, data) => {
if (err) throw err; //EVIL!!!
let id = req.parsedURL.query.id;
if (!id) id = "index";
if (fs.existsSync("pages/" + id + ".html")) {
fs.readFile("pages/" + id + ".html", (err2, data2) => {
if (err2) throw err2; //EVIL TWO!!!
res.writeHead(200, "OK", headers);
res.end(
data.toString().replace("{websiteContents}", data2.toString())
);
});
} else {
res.error(404);
}
});
} else if (href == "/") {
res.redirect("/page.svr");
} else {
next();
}
};
module.exports.modInfo = {
name: "Custom server-side JavaScript",
version: "0.0.0",
};
Instead, you should handle errors gracefully using res.error
function:
Correct Error Handling:
//Much better!
module.exports = (req, res, logFacilities, config, next) => {
let headers = config.getCustomHeaders();
headers["Content-Type"] = "text/html; charset=utf8";
if (req.parsedURL.pathname == "/page.svr") {
fs.readFile(".template", (err, data) => {
if (err) {
res.error(500, err);
return;
}
let id = req.parsedURL.query.id;
if (!id) id = "index";
id = id
.replace(/\\/g, "/")
.replace(/(?:\/|^)\.\.(?=(\/|$))/g, "$1")
.replace(/\/+/g, "/"); //Poor mans path sanitiation
if (fs.existsSync("pages/" + id + ".html")) {
fs.readFile("pages/" + id + ".html", (err2, data2) => {
if (err2) {
res.error(500, err2);
return;
}
res.writeHead(200, "OK", headers);
res.end(
data.toString().replace("{websiteContents}", data2.toString())
);
});
} else {
res.error(404);
}
});
} else if (href == "/") {
res.redirect("/page.svr");
} else {
next();
}
};
module.exports.modInfo = {
name: "Custom server-side JavaScript",
version: "0.0.0",
};
By using res.error
, you can handle errors effectively and provide appropriate error responses to the client, preventing SVR.JS from crashing due to unhandled exceptions.
Main callback API (module.exports
)
Added in SVR.JS 4.0.0
This API includes proxy requests, which don’t use CONNECT method. It’s possible to determine, if the request comes from the proxy with req.isProxy
property.
SVR.JS applies mods for request URLs beginning with “http://” or with “https://” (proxy through GET or POST method, non-proxy requests have request URLs beginning with ”/”) only if module.exports.proxy method is present or if module.exports.proxySafe property is set to true
.
req
Added in SVR.JS 4.0.0
req object is almost same, as req object in Node.JS
req.socket.realRemoteAddress
Added in SVR.JS 4.0.0
A property containing IP address, from which request originally went from, if request is sent through reverse proxy.
You can specify generic request IP variable using const reqip = req.socket.realRemoteAddress ? req.socket.realRemoteAddress : req.socket.remoteAddress
req.socket.realRemotePort
Added in SVR.JS 4.0.0
A property containing port number, from which request originally went from, if request is sent through reverse proxy. (for X-Forwarded-For header, it will be null)
You can specify generic request IP variable using const reqip = req.socket.realRemotePort ? req.socket.realRemotePort : req.socket.remotePort
req.socket.originalRemoteAddress
Added in SVR.JS 4.0.0
A property containing IP address, from which proxy request came from. If the request isn’t a proxy request, it will be undefined
.
req.socket.originalRemotePort
Added in SVR.JS 4.0.0
A property containing port number, from which proxy request came from. If the request isn’t a proxy request, it will be undefined
.
req.url
Added in SVR.JS 4.0.0
A property containing request URL after all processing (URL rewriting too).
req.parsedURL
Added in SVR.JS 4.0.0
A property containing parsed request URL created by a custom URL parser (compatible with legacy URL parser: url.parse()
)
req.originalParsedURL
Added in SVR.JS 4.0.0
A property containing parsed request URL (before URL rewriting) created by a custom URL parser (compatible with legacy URL parser: url.parse()
)
req.isProxy
Added in SVR.JS 4.0.0
A property that determines if request is a proxy request or not.
req.authUser
Added in SVR.JS 4.0.0
The name of authenticated HTTP user. If the user wasn’t authenticated, the property would be null.
res
Added in SVR.JS 4.0.0
res object is almost same, as res object in Node.JS
res.socket.realRemoteAddress
Added in SVR.JS 4.0.0
A property containing IP address, from which request originally went from, if request is sent through reverse proxy.
You can specify generic request IP variable using const reqip = req.socket.realRemoteAddress ? req.socket.realRemoteAddress : req.socket.remoteAddress
res.socket.realRemotePort
Added in SVR.JS 4.0.0
A property containing port number, from which request originally went from, if request is sent through reverse proxy. (for X-Forwarded-For header, it will be null)
You can specify generic request IP variable using const reqip = req.socket.realRemotePort ? req.socket.realRemotePort : req.socket.remotePort
res.socket.originalRemoteAddress
Added in SVR.JS 4.0.0
A property containing IP address, from which proxy request came from. If the request isn’t a proxy request, it will be undefined
.
res.socket.originalRemotePort
Added in SVR.JS 4.0.0
A property containing port number, from which proxy request came from. If the request isn’t a proxy request, it will be undefined
.
res.writeHead(statusCode[, statusMessage][, headers])
Added in SVR.JS 4.0.0
Parameters:
- statusCode - the response status code (String)
- statusMessage - the response status message (optional; String)
- headers - the response headers (optional; Object)
Returns: res property.
The difference between res.writeHead in Node.JS, and in SVR.JS is that in SVR.JS it writes into server log, doesn’t invoke a warning about unused status code string, and if called multiple times will emit a warning, instead of throwing an error, which could crash SVR.JS.
res.setHeader(name, value)
Added in SVR.JS 4.0.0
Parameters:
- name - the response header name (String)
- value - the response header value (optional; String or Array)
The difference between res.setHeader in Node.JS, and in SVR.JS is that in SVR.JS it doesn’t invoke a warning about HTTP/1.x headers being not allowed in HTTP/2.
Custom headers defined in config.json are set by default.
res.head
Added in SVR.JS 4.0.0
HTML head read from either .head or head.html file.
res.foot
Added in SVR.JS 4.0.0
HTML foot read from either .foot or foot.html file.
res.responseEnd(body)
Added in SVR.JS 4.0.0
Parameters:
- body - message you want to send before ending response (String or Buffer)
Sends response message (along with custom head and foot) specified by body parameter.
res.error(errorCode[, extName][, stack][, ch])
Added in SVR.JS 4.0.0
Parameters:
- errorCode - HTTP error code (Number)
- extName - extension name, which caused an error (optional; String)
- stack - error stack (optional; String or Error)
- ch - custom HTTP headers for error (optional; Object)
Invokes HTTP error code. If it’s unavailable, invokes 501 error code.
res.redirect(dest[, isTemporary][, keepMethod][, headers])
Added in SVR.JS 4.0.0
Parameters:
- dest - destination of redirect (String)
- isTemporary - if true, then redirect with 302 code. Else redirect with 301 code. When keepMethod parameter is set to true, then redirect with 307 code, when isTemporary is true or with 308 code otherwise. (optional; Boolean)
- keepMethod - if true, then redirect with either 307 or 308 code. Else redirect with etiher 301 or 302 code. (optional; Boolean; SVR.JS 3.13.0 or later)
- headers - custom HTTP headers for redirect (optional; Object)
Redirects HTTP client to specific destination.
logFacilities
Added in SVR.JS 4.0.0
The log facilities for SVR.JS.
logFacilities.climessage(message)
Added in SVR.JS 4.0.0
Parameters:
- message - message you want to send to server console (String)
Sends CLI message to server console.
logFacilities.reqmessage(message)
Added in SVR.JS 4.0.0
Parameters:
- message - message you want to send to server console (String)
Sends request message to server console.
logFacilities.resmessage(message)
Added in SVR.JS 4.0.0
Parameters:
- message - message you want to send to server console (String)
Sends response message to server console.
logFacilities.errmessage(message)
Added in SVR.JS 4.0.0
Parameters:
- message - message you want to send to server console (String)
Sends response error message to server console.
logFacilities.locerrmessage(message)
Added in SVR.JS 4.0.0
Parameters:
- message - message you want to send to server console (String)
Sends local error message to server console.
logFacilities.locwarnmessage(message)
Added in SVR.JS 4.0.0
Parameters:
- message - message you want to send to server console (String)
Sends local warning message to server console.
logFacilities.locmessage(message)
Added in SVR.JS 4.0.0
Parameters:
- message - message you want to send to server console (String)
Sends local message to server console.
config
Added in SVR.JS 4.0.0
This object contains properties from config.json file.
config.wwwroot
Added in SVR.JS 4.2.0
A normalized path to the webroot. In SVR.JS versions prior to 4.2.0, config.wwwroot refers to the wwwroot property from config.json file.
config.getCustomHeaders()
Added in SVR.JS 4.0.0
Returns: Object property contains custom headers.
This methods retrieves custom headers from config.json file. Returned object additionally includes Server header.
config.generateServerString()
Added in SVR.JS 4.0.0
Returns: The generated server string.
This methods generated the string which is used to identify a web server (the same string as in the “Server” header).
next()
Added in SVR.JS 4.0.0
Invokes next SVR.JS mod callback, SVR.JS server-side JavaScript callback or main SVR.JS callback.
Proxy callback API (module.exports.proxy
)
Added in SVR.JS 4.0.0
req
Added in SVR.JS 4.0.0
req object is the same, as req object in Node.JS
socket
Added in SVR.JS 4.0.0
socket object is the same, as socket object in Node.JS
head
Added in SVR.JS 4.0.0
head object is the same, as head object in Node.JS
logFacilities
Added in SVR.JS 4.0.0
See logFacilties in main callback API
config
Added in SVR.JS 4.0.0
See config in main callback API
next()
Added in SVR.JS 4.0.0
See next in main callback API
Global variables (for use in callback APIs)
process.versions.svrjs
Added in SVR.JS 4.0.0
A property containing SVR.JS version.
process.serverConfiguration
Added in SVR.JS 4.0.0
A property containing SVR.JS configuration from config.json file.
process.dirname
Added in SVR.JS 4.0.0
A property containg the SVR.JS installation directory.
process.filename
Added in SVR.JS 4.0.0
A property containg the path to the SVR.JS script.
process.err4xxcounter
Added in SVR.JS 4.0.0
A property containg the count of 4xx HTTP errors.
process.err5xxcounter
Added in SVR.JS 4.0.0
A property containg the count of 5xx HTTP errors.
process.reqcounter
Added in SVR.JS 4.0.0
A property containg the count of HTTP requests.
process.malformedcounter
Added in SVR.JS 4.0.0
A property containg the count of malformed HTTP requests.