This repository has been archived on 2024-09-12. You can view files and clone it, but cannot push or open issues or pull requests.
svrjs-blog/source/_posts/JSGI-SVR-JS-has-implemented-it.md
2024-03-15 23:24:27 +01:00

2.3 KiB

title date tags categories
JSGI? SVR.JS has implemented it! 2023-08-11 19:56:08
jsgi
javascript
News
Tips

We have recently added support for PHP-CGI and SCGI. We have implemented JSGI in SVR.JS through new YellowSquare mod. We have more specifically implemented JSGI Level 0/A Draft 2 Proposal (aka JSGI 0.3). JSGI (JavaScript Gateway Interface) is an interface between JavaScript web applications and web servers. It is inspired by Rack by Ruby and WSGI by Python. JSGI is included in and further developed by the CommonJS project. Since SVR.JS is written in JavaScript, we could easily implement JSGI. This blog post will instruct you, how to set up JSGI web applications on SVR.JS.

Setting up JSGI

First of all, download and install SVR.JS web server. You can also use create-svrjs-server tool or SVR.JS installer to install SVR.JS.

After setting up SVR.JS, download and install YellowSquare to mods directory.

JSGI web applications in YellowSquare have .jsgi or .jsgi.js extensions and reside in jsgi-bin directory in the web root.

Create an example JSGI web application in <webroot>/jsgi-bin/hello.jsgi with those contents:

var util = require("util");

exports.app = function(request) {
  var requestObjectJson = util.inspect(request);
  return {
    status: 200,
    headers: {
      "Content-Type": "text/html"
    },
    body: [
      "<!DOCTYPE html><html><head><title>Hello World!</title></head><body><h1>Hello World!</h1><p>JSGI request object:</p><code>",
      requestObjectJson.replace(/&/g,"&amp;").replace(/  /g," &nbsp;").replace(/>/g,"&gt;").replace(/</g,"&lt;").replace(/[\r\n]+/g,"<br/>"),
      "</code></body></html>"
    ]
  }
}; 

After creating JSGI application, run SVR.JS using node svr.js or bun run svr.js and visit JSGI page (for example http://localhost/jsgi-bin/hello.jsgi). You will then see this page: JSGI "Hello World"

We have set up JSGI! You need to note that every change in JSGI application will require restart of SVR.JS in order to be applied. Also, when JSGI error occurs, it may be printed into server log, crash the server, or invoke 500 error like one below: JSGI 500 Internal Server Error