- startServer example
- startServer parameters
- startServer return value
startServeris an async function starting a server.
Implemented in src/server/start-server.js, you can use it as shown below.
protocolis a string which ie either "http" or "https".
This parameter is optional with a default value of
"http"If you use https protocol a default self signed certificate will be used.
It can be found inside /server/signature.js.
You may want to add this certificate to your system/browser trusted certificates.
You can also pass your own certificate using signature parameter.
The code below is a basic example showing how you could pass your own certificate.
import { readFileSync } from "fs"
import { startServer } from "@dmail/server"
startServer({
protocol: "https",
signature: {
privateKey: readFileSync(`${__dirname}/ssl/private.pem`),
certificate: readFileSync(`${__dirname}/ssl/cert.pem`),
},
})
ipis a string representing the ip server will listen.
This parameter is optional with a default value of
"127.0.0.1"You can pass an empty string to listen any ip.
ipis a number representing the port server will listen.
This parameter is optional with a default value of
0A value of 0 means server will listen to a random available port.
In that case, if you want to know the listened port use origin value returned by startServer.
forcePortis a boolean controlling if process using the port will be killed
This parameter is optional with a default value of
falsePassing forcePort to true when port is 0 will throw because it makes no sense.
requestToResponseis a function responsible to generate a response from a request.
This parameter is optional with a default value of
() => nullWhen requestToResponse returns null or undefined server respond to that request with 501 Not implemented.
Below are more information on request and response objects.
requestis an object representing an http request
request are passed as first argument to requestToResponse, see below a request example
{
origin: "http://127.0.0.1:8080",
ressource: "/index.html?param=1",
method: "GET",
headers: { accept: "text/html" },
body: undefined,
}When underlying http request method is GET or HEAD, request.body is undefined.
When underlying http request method is POST, PUT, PATCH, request.body is an observable object.
The following code snippet can be used to get request.body as string:
const readRequestBodyAsString = (requestBody) => {
return new Promise((resolve, reject) => {
const bufferArray = []
requestBody.subscribe({
error: reject,
next: (buffer) => {
bufferArray.push(buffer)
},
complete: () => {
const bodyAsBuffer = Buffer.concat(bufferArray)
const bodyAsString = bodyAsBuffer.toString()
resolve(bodyAsString)
},
})
})
}
responseis an object describing an http response.
response are returned must be returned by the code you write inside requestToResponse, see below some response examples:
- response with a body declared with a string
const response = {
status: 200,
headers: { "content-type": "text/plain" },
body: "Hello world",
}- response with a body declared with a buffer
const response = {
status: 200,
headers: { "content-type": "text/plain" },
body: Buffer.from("Hello world"),
}- response with a body declared with a readable stream
const { createReadStream } = require("fs")
const response = {
status: 200,
headers: { "content-type": "text/plain" },
body: createReadStream("/User/you/folder/file.txt"),
}- response with a body declared with an observable body
const response = {
status: 200,
headers: { "content-type": "text/plain" },
body: {
[Symbol.observable]: () => {
return {
subscribe: ({ next, complete }) => {
next("Hello world")
complete()
},
}
},
},
}All parameters starting with accessControl are related to cross origin ressource sharing, also called CORS.
As soon as you pass accessControlAllowRequestOrigin or accessControlAllowedOrigins it means your server use CORS.
When using CORS all your response will contain CORS headers, even a 500 response.
accessControlAllowedOriginsis an array of origins allowed when requesting your server.
This parameter is optional with a default value of
[]
accessControlAllowedMethodsis an array or methods allowed when requesting your server.
This parameter is optional with a default value of
["GET", "POST", "PUT", "DELETE", "OPTIONS"]
accessControlAllowedHeadersis an array of headers allowed when requesting your server.
This parameter is optional with a default value of
["x-requested-with"]
accessControlAllowRequestOriginis a boolean controlling if request origin is auto allowed.
This parameter is optional with a default value of
falseUse this parameter to allow any origin.
accessControlAllowRequestMethodis a boolean controlling if request method is auto allowed
This parameter is optional with a default value of
falseUse this parameter to allowed any request method.
accessControlAllowRequestHeadersis a boolean controlling if request headers are auto allowed
This parameter is optional with a default value of
falseUse this parameter to allowed any request headers.
accessControlAllowCredentialsis a boolean controlling if request credentials are allowed when requesting your server.
This parameter is optional with a default value of
false
accessControlMaxAgeis a number representing an amount of seconds that can be used by client to cache access control headers values.
This parameter is optional with a default value of
600
logLevelis a string controlling how much logs server will write in the console.
This parameters is otional with a default value of
"info"— see jsenv/jsenv-logger#logLevel
stopOnSIGINTis a boolean controlling if server stops itself when process SIGINT is occurs.
This parameters is otional with a default value of
trueSIGINT occurs when you hit ctrl+c in your terminal for instance.
stopOnSIGINTis a boolean controlling if server stops itself when process exits.
This parameters is otional with a default value of
true
stopOnInternalErroris a boolean controlling if server stops itself whenrequestToResponseproduce a 500.
This parameters is otional with a default value of
false
keepProcessAliveis a boolean controlling if server keeps the process alive.
This parameters is otional with a default value of
trueWhen false, if nothing keeps the process alive node process will end even if your server is still listening.
startedCallbackis a function called when server starts listening.
This parameters is otional with a default value of
() => {}startedCallback receives one argument being an object with an origin property representing the server origin like http://127.0.0.1:8080.
stoppedCallbackis a function called when server stops.
This parameters is otional with a default value of
() => {}stoppedCallback receives one argument being an object with a reason property representing why the server stopped.
Each possible reason is an object you can import like this:
import {
STOP_REASON_INTERNAL_ERROR,
STOP_REASON_PROCESS_SIGINT,
STOP_REASON_PROCESS_BEFORE_EXIT,
STOP_REASON_PROCESS_HANGUP_OR_DEATH,
STOP_REASON_PROCESS_DEATH,
STOP_REASON_PROCESS_EXIT,
STOP_REASON_NOT_SPECIFIED,
} from "@dmail/server"reason might also be a value you passed yourself:
import { startServer } from "@dmail/server"
const { stop } = await startServer({
stoppedCallback: ({ reason }) => {
reason === 42
},
})
stop(42)startServer return value signature is
{
getStatus, origin, nodeServer, agent, stop, stoppedPromise
}The properties not documented below are not meants to be used.
originis a string representing the url server is listening to.
It is part of value returned by startServer and an example origin could be:
"http://127.0.0.1:65289"
nodeServeris the http_server instance used internally by the server.
It is part of value returned by startServer. It exists in case you need to do something on the node server itself.
— see http_server documentation on node.js
stopis an async function asking server to be stopped
It is part of value returned by startServer and could be used like this:
import { startServer } from "@dmail/server"
const { stop } = await startServer()
stop()Stop returns a promise resolved when server is completely stopped.
If you call stop without argument, promise is resolved with STOP_REASON_NOT_SPECIFIED, otherwise it is resolved with the value your provided.
stoppedPromiseis a promise resolved with a reason when server is stopped
It is part of value returned by startServer and could be used like this:
import { startServer } from "@dmail/server"
const { stoppedPromise } = await startServer()
stoppedPromise.then((reason) => {
console.log(`server stopped because ${reason}`)
})stoppedPromise exists because server can be stopped calling stop or automatically by parameters like stopOnSIGINT.