sprucehttp_sjs
v2.2.0
Published
A module for responding to requests within SpruceHTTP in an SJS file
Maintainers
Readme
SpruceHTTP SJS:
A module for responding to requests within SpruceHTTP in an SJS file.
Table of Contents:
- Table of Contents
- Documentation
- streamMode()
- writeStatusLine(statusCode, reasonPhrase)
- writeHeader(name, value)
- writeData(data)
- writeDataAsync(data)
- clearResponse()
- end()
- siteConfig
- requestIP
- method
- path
- pathInfo
- query
- queryValue(key)
- httpVersion
- headers
- headerValue(name)
- body
- bodyStream([options])
- mTlsPeerCertificate
- requestObject
- updateConfig(newConfig)
- modifyRequest(newRequest)
Documentation:
Importing the module:
const sjs = require("sprucehttp_sjs");streamMode():
Sets the response into stream mode. This cannot be undone for the duration of the script, and should be the first action performed if this is the intended mode.
Stream mode means that responses are not buffered by the webserver, and thus are sent immediately as they're received from the SJS script. This means that the status line and headers must be sent first before the data, and the \r\n after the headers must be sent by the script as well.
Returns a Promise that resolves when the server acknowledges the switch to stream mode.
await sjs.streamMode(); // Set the response to stream mode.writeStatusLine(statusCode[, reasonPhrase]):
statusLine:number: The HTTP status code to send.reasonPhrase:string: Optional. The reason phrase to send.
Writes the status line to the response.
Returns a Promise that resolves when the server acknowledges the status line.
To send a 200 "OK" response, without needing to specify the reason phrase.
await sjs.writeStatusLine(200);To send a 418 "I'm a teapot" response, with a specified reason phrase.
await sjs.writeStatusLine(418, "I'm a teapot");writeHeader(name, value):
name:string: The name of the header to send.value:string: The value of the header to send.
Writes a header to the response.
Returns a Promise that resolves when the server acknowledges the header.
To write the "Content-Type: text/html" header.
await sjs.writeHeader("Content-Type", "text/html");writeData(data):
data:string | Buffer: The data to send.
Writes data (the body) to the response. When not in stream mode, the Content-Length header is automatically updated.
This function is deprecated. Use writeDataAsync instead, as data cannot be reliably sent synchronously.
Writes text data to the body.
sjs.writeData("Hello, world!");Writes binary data (a picture, in this case) to the body.
const fs = require('fs');
sjs.writeData(fs.readFileSync("image.png", 'binary'));writeDataAsync(data):
data:string | Buffer: The data to send.
Writes data (the body) to the response asynchronously. When not in stream mode, the Content-Length header is automatically updated.
Returns a Promise that resolves when the data has been written.
Writes text data to the body.
await sjs.writeDataAsync("Hello, world!");Writes binary data (a picture, in this case) to the body.
const fs = require('fs');
await sjs.writeDataAsync(fs.readFileSync("image.png", 'binary'));clearResponse():
Clears the currently written response and resets the status line, headers, and body. This is useful when you want to send a different response than the one you have already written.
Returns a Promise that resolves when the response has been cleared.
This function does not work in stream mode.
await sjs.writeStatusLine(418, "I'm a teapot");
await sjs.writeHeader("Content-Type", "text/html");
await sjs.writeData("<h1>I'm a teapot</h1>");
// Be serious
await sjs.clearResponse();
await sjs.writeStatusLine(200);
await sjs.writeHeader("Content-Type", "text/html");
await sjs.writeData("<h1>I'm <i>not</i> a teapot</h1>");end():
Ends the response. Responses are automatically ended when the SJS script exits, but this function allows you to end the response early. This is useful if you want to stop sending data before the script has finished executing.
Returns a Promise that resolves when the response has been ended.
await sjs.writeStatusLine(200);
await sjs.writeHeader("Content-Type", "text/html");
await sjs.writeData("<h1>Hello, world!</h1>");
await sjs.end(); // End the response early
// Any further writes will be ignoredsiteConfig:
Returns the site-specific configuration set in your config file.
Returns an object representing the site configuration.
console.log(sjs.siteConfig);
/*
{
"type": "local",
"location": "./",
"upgradeInsecure": true,
"directoryListing": true,
"sjs": true,
"headers": {
"Access-Control-Allow-Origin": "*"
},
"ssl": {
"key": "./ssl/key.pem",
"cert": "./ssl/cert.pem",
"minVersion": "TLSv1.2",
"maxVersion": "TLSv1.3"
}
}
*/requestIP:
Returns the requestor's IP address.
console.log(sjs.requestIP);
// ::ffff:198.51.100.163method:
Returns the request method.
console.log(sjs.method);
// getpath:
Returns the request path.
console.log(sjs.path);
// /index.sjspathInfo:
Returns the request's info path.
// Using path /index.sjs/info
console.log(sjs.path);
console.log(sjs.pathInfo);
// /index.sjs
// /infoquery:
Returns the request query.
console.log(sjs.query);
/*
{
"name": "John",
"age": "42"
}
*/queryValue(key):
key:string: The key of the query to get.
Returns the value of a query parameter.
console.log(sjs.queryValue("name"));
// JohnhttpVersion:
Returns the HTTP version of the request.
console.log(sjs.httpVersion);
// http/1.1headers:
Returns the request headers.
console.log(sjs.headers);
/*
{
"connection": "keep-alive",
"host": "localhost:8080",
"upgrade-insecure-requests": "1",
"user-agent": "Bruh/1.0 (Macintosh; PPC Mac OS X 7_0_1) AppleBruhKit 1.3 (XHTML, like IE) Netscape/69.420 Moment/360 NoScope/1.0"
}
*/headerValue(name):
name:string: The name of the header to get.
Returns the value of a header.
console.log(sjs.headerValue("user-agent"));
// Bruh/1.0 (Macintosh; PPC Mac OS X 7_0_1) AppleBruhKit 1.3 (XHTML, like IE) Netscape/69.420 Moment/360 NoScope/1.0body:
Returns the request body as a buffer.
console.log(sjs.body.toString("utf8"));
// Hello, world!bodyStream([options]):
options:BufferEncoding | ReadStreamOptions: Optional. The options to pass to fs.createReadStream. Returns the request body as a ReadStream.
console.log(sjs.bodyStream().read(13).toString("utf8"));
// Hello, world!mTlsPeerCertificate:
Returns details about the mTLS peer's certificate, if present.
console.log(sjs.mTlsPeerCertificate.subject.CN);
// sprucehttp.comrequestObject:
Returns the full request object.
console.log(sjs.requestObject);
// {
// "version": "HTTP/1.1",
// ... rest of request object ...
// }updateConfig(newConfig):
newConfig:object: The new site configuration to set.
Updates the site-specific configuration for the request. You must provide a complete configuration object.
This is only effective during a pre-request hook.
Returns a Promise that resolves when the configuration has been updated.
sjs.updateConfig({
// New configuration object
});modifyRequest(newRequest):
newRequest:object: The new request object to set.
Modifies the request object for the request. You must provide a complete request object.
This is only effective during a pre-request hook.
Returns a Promise that resolves when the request has been modified.
sjs.modifyRequest({
// New request object
});