[PYTHON] I tried collecting one-liner web servers

I tried collecting one-liner web servers

You may be messing with JavaScript on the client side and suddenly step into an area that cannot be executed with a local file. Nowadays, HTTPS is required or you may want to try HTTP2. For the time being, I've stepped into Web Workers, but other things like WebRTC ... (remembering) ... (not found) ... etc.

In such a case, it is troublesome to start Apache and nginx one by one, so I will leave a little search result.

[2018/4/18 postscript] Recently, the need to use HTTPS is increasing. In response to this, the number of methods that support HTTPS has increased, so we cannot cover all of them, but we have added and changed as much as possible.

Python (SimpleHTTPServer)

In Python, a "-m" option has been added to run the module as a script (although it seems to be limited to version 2.4 and later). Use this option to run SimpleHTTPServer, one of the standard libraries, in one liner. An example of startup and an access log are shown. The standard port number is 8000.

Example of listening on port 8000


$  python -m SimpleHTTPServer
Serving HTTP on 0.0.0.0 port 8000 ...
127.0.0.1 - - [09/Jan/2014 11:21:09] "GET / HTTP/1.1" 200 -

It is good that the access log remains properly. If you want to change the port number, specify the port number at the end.

Example of listening on port 3000


$  python -m SimpleHTTPServer 3000
Serving HTTP on 0.0.0.0 port 3000 ...

Reference: One-liner for starting a Web server immediately with one command (Ruby or Python)

Python 3.x

I haven't tried it, but it seems to work with Python 3.x series as follows.

Example of listening on port 8000


$ python -m http.server 8000

Reference: Web server with one liner

Ruby (WEBRick)

A library called webrick is attached to Ruby as standard, so you can use it to set up a web server. In the example below, only the document root and port number (8000) are specified, but other settings can be made. The standard port number is 80. Note that if you do not specify the port number, it will stop with an error if you do not have administrator privileges.

Example of listening on port 8000


$ ruby -rwebrick -e 'WEBrick::HTTPServer.new(:DocumentRoot => "./", :Port => 8000).start'
[2014-01-09 13:49:12] INFO  WEBrick 1.3.1
[2014-01-09 13:49:12] INFO  ruby 1.9.3 (2013-06-27) [x86_64-darwin12.4.0]
[2014-01-09 13:49:12] INFO  WEBrick::HTTPServer#start: pid=9479 port=8000
localhost - - [09/Jan/2014:13:49:15 JST] "GET / HTTP/1.1" 200 2377
- -> /

It is good that the access log remains here as well.

~~ * To stop, use the -KILL option for the kill command. ~~ When I tried it earlier, I was able to stop it with ctrl + C.

Old way to stop (now ctrl+Stops at C)


$ ps aux | grep ruby
Look up the webrick process number
$ kill -KILL process number

Reference: One-liner for starting a Web server immediately with one command (Ruby or Python)

HTTPS edition with Ruby (WEBRick)

When I checked WEBRick for the first time in a long time, I found that it can easily support HTTPS. In the following example, the certificate is automatically generated and then listens on port 8000. * For HTTPS only. You cannot connect with HTTP.

Example of listening on HTTPS on port 8000


$ ruby -rwebrick -rwebrick/https -e 'WEBrick::HTTPServer.new(:DocumentRoot => "./", :Port => 8000, :SSLEnable => true, :SSLCertName => [["CN", WEBrick::Utils::getservername]] ).start'
[2016-06-01 14:10:36] INFO  WEBrick 1.3.1
[2016-06-01 14:10:36] INFO  ruby 2.1.4 (2014-10-27) [x86_64-darwin14.0]
................................................................................................................++++++
....++++++
[2016-06-01 14:10:36] INFO
Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number: 1 (0x1)
    Signature Algorithm: sha1WithRSAEncryption
        Issuer: CN=sahara.local
        Validity
            Not Before: Jun  1 05:10:36 2016 GMT
            Not After : Jun  1 05:10:36 2017 GMT
        Subject: CN=sahara.local
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                Public-Key: (1024 bit)
                Modulus:
                    00:b7:e4:37:9e:86:40:dd:cb:01:b2:a7:a8:53:db:
                    42:e8:81:0f:a9:23:63:d9:6c:6a:6a:13:0f:bc:66:
                    ed:ac:04:6c:93:1d:82:7b:22:6f:11:fc:cd:b7:ab:
                    a8:6b:fc:fc:60:e8:18:cc:52:95:b4:1a:aa:8c:1e:
                    01:cb:fa:14:0b:03:f0:3e:9e:d2:d4:5d:44:b2:83:
                    e4:de:49:5c:37:7d:1a:2b:97:a7:82:e9:d9:cb:c0:
                    fa:f5:5b:92:54:29:5c:e4:fe:c4:ed:a0:2f:3b:da:
                    83:09:e2:12:d8:01:84:9f:60:80:9c:5a:1b:12:70:
                    be:97:e1:3c:34:b6:fd:80:29
                Exponent: 65537 (0x10001)
        X509v3 extensions:
            X509v3 Basic Constraints:
                CA:FALSE
            X509v3 Key Usage:
                Key Encipherment
            X509v3 Subject Key Identifier:
                00:0C:DD:F6:BD:66:22:72:82:DA:82:20:9C:54:E6:12:64:5E:90:15
            X509v3 Extended Key Usage:
                TLS Web Server Authentication
            Netscape Comment:
                Generated by Ruby/OpenSSL
            X509v3 Authority Key Identifier:
                keyid:00:0C:DD:F6:BD:66:22:72:82:DA:82:20:9C:54:E6:12:64:5E:90:15
                DirName:/CN=sahara.local
                serial:01

    Signature Algorithm: sha1WithRSAEncryption
         5b:ae:8f:06:7f:07:a2:ff:25:f1:4e:b6:04:c7:9f:fb:e0:aa:
         54:3d:b8:ab:54:a5:cf:e0:94:52:d1:e5:03:0e:8f:73:13:6f:
         34:f4:e7:88:93:9e:69:df:43:c2:33:5d:cc:48:4b:2a:84:48:
         a4:a2:7d:e8:e1:82:7e:3e:a4:23:34:c9:72:f3:5b:52:c7:41:
         6a:99:29:16:70:ee:bf:bd:d5:38:92:9b:0a:0d:9a:70:6f:a8:
         c3:18:60:df:73:45:41:29:3d:b3:6a:59:23:fe:1f:14:e0:cf:
         a1:db:09:50:06:7c:a3:81:95:c0:78:29:3c:71:ce:ac:aa:20:
         98:06
[2016-06-01 14:10:36] INFO  WEBrick::HTTPServer#start: pid=7246 port=8000
localhost - - [01/Jun/2016:14:10:55 JST] "GET / HTTP/1.1" 200 4257
- -> /

When I try to connect with a web browser, a note such as "This connection does not protect privacy" (for Chrome) or "It is not a secure connection" (for Firefox) is displayed.

In the case of Chrome, you can display the page by clicking "Access localhost (not secure)" that appears when you click "Advanced".

In the case of Firefox, it is a little complicated, and you can treat this site as an exception by clicking "Add Exception" that appears when you click "Error Details" and then clicking "Approve Security Exception" in the dialog. However, if you restart the HTTPS server after that, the certificate will be updated and the connection will be refused (error code: SEC_ERROR_REUSED_ISSUER_AND_SERIAL). In this case, you need to delete the certificate registered in Firefox. See Reference 2 for details.

~~ The above method automatically creates a certificate, but you can also use an existing certificate. It will be too long to be called a one-liner, so I will omit it, but please see Reference 1 for details. ~~

Reference 1 has disappeared for each domain and could not be found by searching by title, so I will add a method to use an existing certificate.

First, prepare the private key and certificate. If you already have a certificate, please skip it. In the example below, the country name is only JP, and the following questions are not answered.

Creating a private key and certificate


$ openssl req -new -newkey rsa:2048 -sha256 -days 365 -nodes -x509 -keyout localhost.key -out localhost.crt
Generating a 2048 bit RSA private key
.............................................................+++
..............................................................................................................................................................+++
writing new private key to 'localhost.key'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:JP
State or Province Name (full name) [Some-State]:
Locality Name (eg, city) []:
Organization Name (eg, company) [Internet Widgits Pty Ltd]:
Organizational Unit Name (eg, section) []:
Common Name (e.g. server FQDN or YOUR name) []:
Email Address []:
$ ls
localhost.crt	localhost.key

Start a Web server that supports HTTPS using the certificate created above or an existing certificate created separately. As a one-liner, it is a little long, so be careful not to make a mistake.

Example of listening on HTTPS on port 8000


$ ruby -rwebrick -rwebrick/https -e 'WEBrick::HTTPServer.new(:DocumentRoot => "./", :Port => 8000, :SSLEnable => true, :SSLPrivateKey => OpenSSL::PKey::RSA.new(File.open("localhost.key").read), SSLCertificate: OpenSSL::X509::Certificate.new(File.open("localhost.crt").read), :SSLCertName => [["CN", WEBrick::Utils::getservername]] ).start'
[2018-04-18 03:30:53] INFO  WEBrick 1.3.1
[2018-04-18 03:30:53] INFO  ruby 2.3.1 (2016-04-26) [x86_64-darwin14]
[2018-04-18 03:30:53] INFO
Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number:
            c7:92:94:c6:4b:1f:75:65
    Signature Algorithm: sha256WithRSAEncryption
        Issuer: C=JP, ST=Some-State, O=Internet Widgits Pty Ltd
        Validity
            Not Before: Apr 17 18:23:43 2018 GMT
            Not After : Apr 17 18:23:43 2019 GMT
        Subject: C=JP, ST=Some-State, O=Internet Widgits Pty Ltd
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                Public-Key: (2048 bit)
                Modulus:
                    00:c3:c7:93:ee:fb:00:4f:b1:b4:6a:8d:b8:13:7e:
                    b0:f9:7e:63:43:21:40:1c:c2:2e:ce:f4:fa:68:37:
                    03:8b:1b:e1:c3:de:3c:4e:23:d3:9b:b8:78:d3:47:
                    3c:78:1f:fb:97:43:d3:ec:6f:8d:56:ee:c1:5a:16:
                    a7:84:91:bf:c3:79:e2:d4:33:cd:f3:b5:7d:5b:55:
                    d2:ef:3f:f8:9d:fe:e1:28:04:24:2d:5a:ef:dd:cc:
                    10:ba:2e:d8:ed:65:61:5b:95:1a:11:5c:1a:c3:1d:
                    76:5f:b2:c8:05:66:88:e0:38:03:4b:fd:0a:51:2c:
                    9f:3e:ff:f0:40:66:02:ba:b5:14:d2:c9:09:3a:c0:
                    c3:40:6a:2f:6c:ed:6b:e1:72:f2:19:c2:41:7a:9c:
                    fb:83:81:ab:df:a1:3b:db:29:b1:4d:a6:89:43:28:
                    17:2a:ee:77:47:60:52:66:fa:08:e4:e5:ec:0e:cd:
                    33:1d:e9:86:81:c3:66:d3:40:63:62:f1:da:83:8a:
                    8a:e9:fd:c5:7b:11:13:d6:9a:74:ef:5b:aa:ac:19:
                    59:8d:a6:ae:22:95:c8:b5:5f:05:bd:09:5d:df:6c:
                    09:b0:9f:22:7f:81:ee:4f:42:5c:e9:4c:7e:0c:75:
                    1b:b3:14:4d:32:cf:86:28:0a:a5:d1:f5:64:b6:5f:
                    26:e1
                Exponent: 65537 (0x10001)
        X509v3 extensions:
            X509v3 Subject Key Identifier:
                A7:A1:32:FD:43:80:05:EC:F0:1B:41:0C:3B:0A:05:DE:46:F1:B5:32
            X509v3 Authority Key Identifier:
                keyid:A7:A1:32:FD:43:80:05:EC:F0:1B:41:0C:3B:0A:05:DE:46:F1:B5:32
                DirName:/C=JP/ST=Some-State/O=Internet Widgits Pty Ltd
                serial:C7:92:94:C6:4B:1F:75:65

            X509v3 Basic Constraints:
                CA:TRUE
    Signature Algorithm: sha256WithRSAEncryption
         2b:b0:86:47:9f:29:d0:2d:99:85:7f:52:fd:46:af:5a:ef:97:
         de:98:da:ab:a6:97:4b:3a:16:06:52:ad:ec:9d:37:47:1d:af:
         3d:59:11:43:ca:2e:24:77:88:d3:68:67:cb:53:72:d9:c2:d5:
         a2:26:00:34:26:63:db:1b:86:63:4f:94:ac:20:ee:07:07:67:
         ad:50:67:3a:fa:b8:0a:56:10:9f:e6:c2:80:df:6d:42:2e:cf:
         91:ff:2e:de:02:5a:63:5c:45:0c:e7:8a:0c:a5:42:4d:09:1c:
         1f:c1:28:6b:5e:2e:98:fd:65:d5:83:43:c4:2b:72:f4:61:ca:
         d5:8a:65:4d:10:bd:6b:0a:ce:b5:ea:86:8e:cc:18:61:87:88:
         b0:26:e0:42:22:75:e6:36:12:19:79:52:76:5c:94:f4:3b:7a:
         1e:16:5d:ea:28:1b:a8:b3:f8:aa:49:05:c5:07:f8:5c:7f:99:
         96:cf:f6:d5:71:8d:37:40:94:06:82:d0:d1:67:49:93:1c:29:
         7f:85:18:12:83:4a:0c:95:08:8e:19:e6:07:4a:9e:a1:35:81:
         a6:65:35:d9:ea:a0:cd:b8:6a:c8:f9:fe:0f:b5:1e:bd:df:48:
         64:f1:bb:a4:b6:97:cc:75:fc:40:a5:4c:e9:6b:e4:9a:2f:a0:
         36:d8:39:f8
[2018-04-18 03:30:53] INFO  WEBrick::HTTPServer#start: pid=10166 port=8000
::1 - - [18/Apr/2018:03:30:55 JST] "GET / HTTP/1.1" 200 1996
- -> /

~~ Reference 1: Enable SSL on WEBrick ~~ Reference 2: [Server certificate with the same serial number as others](https://support.mozilla.org/ja/kb/%E4%BB%96%E3%81%A8%E5%90%8C%E3 % 81% 98% E3% 82% B7% E3% 83% AA% E3% 82% A2% E3% 83% AB% E7% 95% AA% E5% 8F% B7% E3% 82% 92% E3% 82 % 82% E3% 81% A4% E3% 82% B5% E3% 83% BC% E3% 83% 90% E8% A8% BC% E6% 98% 8E% E6% 9B% B8)

Ruby (Sinatra)

Ruby has a Sinatra framework, which can also be used to set up a web server in one liner. An example of startup and an access log are shown. The standard port number is 4567. According to the Sinatra format, it will process complicated URLs, but in the following example, index.html will be ignored and "Hello World" will be returned.

Example of listening on port 4567


$ ruby -rsinatra -e 'set :public_folder, "./", get("/"){"Hello world"}'
== Sinatra/1.4.2 has taken the stage on 4567 for development with backup from Thin
>> Thin web server (v1.5.1 codename Straight Razor)
>> Maximum connections set to 1024
>> Listening on localhost:4567, CTRL+C to stop
127.0.0.1 - - [09/Jan/2014 13:56:05] "GET / HTTP/1.1" 200 11 0.0025

To specify the port number, do as follows.

Example of listening on port 8000


$ ruby -rsinatra -e 'set :port, 8000; set :public_folder, "./", get("/"){"Hello world"}'

Reference: How to start a web server with one liner

Example of accepting from other hosts


ruby -rsinatra -e 'set :port, 8000; set :public_folder, "./"; set :environment, :producntion; get("/"){"Hello world"}'

Reference: Sinatra is no longer connected from the outside by default

PHP edition

Web server functions have been incorporated since PHP 5.4.0 (Thanks to tadsan for providing information). According to the documentation, "use it for demos and tests", but it's perfect for this post. In the following example, it is started to use port 8000. The host name and port number cannot be omitted.

Example of accepting only from localhost


$ php -S localhost:8000
PHP 5.4.17 Development Server started at Thu Jan  9 17:35:44 2014
Listening on http://localhost:8000
Document root is /hoge
Press Ctrl-C to quit.
[Thu Jan  9 17:35:48 2014] ::1:59299 [404]: / - No such file or directory

As with the Ruby (Sinatra) edition, you can only connect from localhost as it is. If you want to connect from another host, specify "0.0.0.0" as the host name and start it.

Example of accepting from other hosts


$ php -S 0.0.0.0:8000

Reference: Built-in web server

Ruby (un library)

Until now, it was unchecked, but you can easily set up a web server with Ruby ( Thank you for providing information, Mr. yoshi-taka). According to the documentation, it is part of the un library, which is an alternative utility to Unix basic commands, and it seems that WEBRick actually starts. In the following example, the current directory is set as the document root and it is started to use the 8000 version port. The access log is the same as the base WEBRick. If the port number is omitted, it will try to start on port 80. Compared to Ruby (WEBRick edition) introduced earlier, it has the advantages of "short command" and "can be terminated with ctrl + C".

Example of waiting in 8000 version


$ ruby -run -e httpd . -p 8000
[2014-03-01 11:03:36] INFO  WEBrick 1.3.1
[2014-03-01 11:03:36] INFO  ruby 2.0.0 (2013-06-27) [universal.x86_64-darwin13]
[2014-03-01 11:03:36] INFO  WEBrick::HTTPServer#start: pid=825 port=8000
localhost - - [01/Mar/2014:11:03:49 JST] "GET /test.html HTTP/1.1" 200 94937
- -> /test.html

Reference: library un --Ruby Reference: httpd (Object) --APIdock

Python (CGIHTTPServer)

In the Python area, static Web pages are not enough, and there seems to be a library that can run even CGI with one liner (Thanks to mash76 for providing information). Although it is the name of the library, the name is also Zubari CGI HTTP Server. When I looked it up, it inherited SimpleHTTPServer and supported CGI. Then, prepare a CGI script as a preliminary preparation. Put the CGI script in cgi-bin in the current directory. The example below uses python, but it can be run in other languages as well.

Preparing for CGI


$ mkdir cgi-bin
$ cd cgi-bin
$ cat > index.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
String(hello world.)To display
'''
print "Content-Type: text/plain"
print
print "hello world."
^D (← control+Press D)
$ chmod 755 index.py
$ cd ..
$ tree
.
└── cgi-bin
    └── index.py

Let's start it. In the following example, the current directory is started as the document root. If the port number is omitted, port 8000 will be used. You can complete it with ctrl + C, but please be prepared because an error message will appear at the end.

Example of listening on the standard (8000) port


$ python -m CGIHTTPServer
Serving HTTP on 0.0.0.0 port 8000 ...
127.0.0.1 - - [02/Dec/2015 12:53:38] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [02/Dec/2015 12:53:39] code 404, message File not found
127.0.0.1 - - [02/Dec/2015 12:53:39] "GET /favicon.ico HTTP/1.1" 404 -
127.0.0.1 - - [02/Dec/2015 12:53:47] "GET /cgi-bin/index.py HTTP/1.1" 200 -

To specify the port number, do as follows.

Example of listening on port 9000


$python -m CGIHTTPServer 9000

Perl edition

I received information that Perl also has a one-liner Web server (Thanks to xtetuji for providing the information). Personally, I haven't used Perl very much, so I'd like to describe it from the installation method.

Cpan settings and Plack installation


$ cpan
(It's quite long. I'll be asked some questions about the installation destination, so enter it properly. I pressed Enter because all the standard settings were fine. Finally, ask if I can set environment variables in the startup script. It will be.)
$ sudo cpan Task::Plack
(This is also quite long. Download the necessary modules etc. After waiting, you will be asked if the standard installation is okay, so please answer appropriately. I chose Y. Also, sudo first If you run it without it, Permission Denied is displayed, so sudo is added.)

Now, let's execute it so that it listens on port 5000. The command line is a bit long, but you can easily change the document root.

Starting a one-liner web server with Perl


$ plackup -MPlack::App::Directory -e 'Plack::App::Directory->new({root=>$ENV{PWD}})->to_app'
HTTP::Server::PSGI: Accepting connections at http://0:5000/
127.0.0.1 - - [02/Dec/2015:14:01:01 +0900] "GET / HTTP/1.1" 200 31580 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.73 Safari/537.36"
127.0.0.1 - - [02/Dec/2015:14:01:02 +0900] "GET /favicon.ico HTTP/1.1" 404 9 "http://localhost:5000/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.73 Safari/537.36"

Reference: Introduction to Plack: Starting a web server with Plack and doing hello world

node.js (http-server)

Part 1. Global installation of http-server

It seems that node.js also has a one-liner web server. So I will introduce http-server. It is assumed that node.js has been installed. First, install http-server.

Global installation example


$ npm install -g http-server

The document root will be the current directory if there is no public directory. Now, assume that the directory structure is as follows.

Directory configuration example


.
└── public
    └── index.html

Start to use the standard port (8080) from the directory corresponding to the above ".".

Example of listening on port 8080


$ http-server
Starting up http-server, serving ./public
Available on:
  http:127.0.0.1:8080
  http:192.168.0.1:8080 (← Stand by other than localhost)
Hit CTRL-C to stop the server
[Wed, 02 Dec 2015 04:10:35 GMT] "GET /" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.73 Safari/537.36"

Use the -p option to change the port number.

Example of listening on port 8000


$ http-server -p 8000
Starting up http-server, serving ./public
Available on:
  http:127.0.0.1:8000
  http:192/168/0.1:8000
Hit CTRL-C to stop the server

In addition, http-server has an option `` `-o``` to open the Web browser at the same time as starting. If you execute the following, the web browser will open automatically. (If the web browser is already running, the corresponding page will open in a new tab: for chrome)

Example of opening a browser at the same time


$ http-server -p 8000 -o
Starting up http-server, serving ./public
Available on:
  http:127.0.0.1:8000
  http:172.16.11.3:8000
Hit CTRL-C to stop the server
[Wed, 02 Dec 2015 05:10:59 GMT] "GET /" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.73 Safari/537.36"
[Wed, 02 Dec 2015 05:11:00 GMT] "GET /favicon.ico" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.73 Safari/537.36"
[Wed, 02 Dec 2015 05:11:00 GMT] "GET /favicon.ico" Error (404): "Not found"

http-server seems to support HTTPS by using the existing private key and certificate. Please see HTTPS with Ruby (WEBRick) for how to create certificates. The following is an example of listening by HTTPS by specifying the private key and certificate.

Example of listening on HTTP on port 8000


$ http-server -p 8000 -S -C localhost.crt -K localhost.key
Starting up http-server, serving ./public through https
Available on:
  https://127.0.0.1:8000
  https://192.168.1.3:8000
Hit CTRL-C to stop the server

Reference 1: The command line web server called http-server of Node.js is convenient Reference 2: http-server

Part 2. Install http-server locally

In the above example, http-server was installed globally, but in some cases you may want to install it locally. For those people, I would also like to explain about local installation. Local installation does not pollute the environment because the modules are installed under node_modules in the current directory. Let's install it now.

http-Install server locally


$ npm install http-server
[email protected] node_modules/http-server
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected] ([email protected], [email protected])
├── [email protected] ([email protected], [email protected])
├── [email protected] ([email protected], [email protected], [email protected], [email protected])
├── [email protected] ([email protected])
└── [email protected] ([email protected], [email protected])
$

Next is the start of the Web server. I am trying to use port 8000.

http-start server


$ ./node_modules/.bin/http-server -p 8000
Starting up http-server, serving ./
Available on:
  http:127.0.0.1:8000
  http:192.168.0.1:8000
Hit CTRL-C to stop the server

If you have a long command, please use npm bin together (Thanks to kaminaly). The advantage of npm bin is that it can be executed properly even if it is hidden in a subdirectory. In the following example, it is executed after making the current directory public.

http with npm command-start server


$cd public (← even if you cd to public ...)
$ $(npm bin)/http-server -p 8000 (← can be executed. * Originally executed only on this line)
Starting up http-server, serving ./
Available on:
  http:127.0.0.1:8000
  http:192.168.0.1:8000
Hit CTRL-C to stop the server

Part 3. Local installation using package.json

If you have a long start command, please create the following file and use npm. If you want to change the port number, change the value after -p on the 6th line.

package.json


{
  "name": "web",
  "version": "1.0.0",
  "description": "Simple web server",
  "scripts": {
    "start": "http-server -p 8000"
  },
  "author": "suda",
  "license": "ISC",
  "dependencies": {
    "http-server": "^0.8.5"
  }
}

Install http-server using npm. Type the following command in the directory where package.json is located.

package.Install module according to json


$ npm install
npm WARN package.json [email protected] No repository field.
npm WARN package.json [email protected] No README data
[email protected] node_modules/http-server
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected] ([email protected], [email protected])
├── [email protected] ([email protected], [email protected])
├── [email protected] ([email protected])
├── [email protected] ([email protected], [email protected])
└── [email protected] ([email protected], [email protected], [email protected], [email protected])
$

Next, start the web server using npm. The "start" item of "script" in package.json is executed. In addition, it is automatically executed with the path in ~~ ./node_modules/ / bin and the path in ~~ `` `./node_modules/.bin``` (kaminaly). Thank you very much).

$ npm start
> [email protected] start /home/suda
> http-server -p 8000

Starting up http-server, serving ./public
Available on:
  http:127.0.0.1:8000
  http:192.168.0.1:8000
Hit CTRL-C to stop the server

Creating package.json and managing it with npm seems a bit exaggerated, but it has the advantage that it can be used without destroying the environment and it is good for beginners because it is hard to remember.

node.js (serve)

I was told that there is serve as a module similar to http-server (Thanks to kaminaly), so I will try it immediately. Only global installation is explained here, but local installation and local installation by package.json are also possible. Addendum: Added and changed according to the latest version of serve (version 6.5.5 as of April 18, 2018).

Global installation example


$ npm install -g serve

Next, start using the standard port (~~ 3000 ~~ 5000) with the current directory as the document root.

Example of listening on port 5000


$ serve

   ┌─────────────────────────────────────────────────┐
   │                                                 │
   │   Serving!                                      │
   │                                                 │
   │   - Local:            http://localhost:5000     │
   │   - On Your Network:  http://192.168.1.3:5000   │
   │                                                 │
   │   Copied local address to clipboard!            │
   │                                                 │
   └─────────────────────────────────────────────────┘

Use the -p option to change the port number.

Example of listening on port 8000


$ serve -p 8000

   ┌─────────────────────────────────────────────────┐
   │                                                 │
   │   Serving!                                      │
   │                                                 │
   │   - Local:            http://localhost:8000     │
   │   - On Your Network:  http://192.168.1.3:8000   │
   │                                                 │
   │   Copied local address to clipboard!            │
   │                                                 │
   └─────────────────────────────────────────────────┘

It was also possible to apply password authentication. In the following example, the user name is `suda``` and the password is `suda1234```, and the site is set as an authenticated site. User names etc. are set by environment variables, not options.

Example of adding password authentication


$ SERVE_USER=suda SERVE_PASSWORD=suda1234 serve --ah
th
   ┌─────────────────────────────────────────────────┐
   │                                                 │
   │   Serving!                                      │
   │                                                 │
   │   - Local:            http://localhost:5000     │
   │   - On Your Network:  http://192.168.1.3:5000   │
   │                                                 │
   │   Copied local address to clipboard!            │
   │                                                 │
   └─────────────────────────────────────────────────┘

Reference: serve

HTTP2 with node.js (light-server)

In node.js, I was told that there is a module called light-server other than http-server and serve (Thanks to hatappo), so I will try this as well. Only global installation is explained here, but local installation and local installation by package.json are also possible. (Sorry, I haven't tried it due to lack of time)

Global installation example


$ npm install -g light-server

Next, start using the standard port (4000) with the current directory as the document root.

Example of listening on port 4000


$ light-server -s .
light-server is listening at http://0.0.0.0:4000
  serving static dir: .

GET /index.html 200 29.438 ms - -

Use the -p option to change the port number.

Example of listening on port 8000


$ light-server -s . -p 8000
light-server is listening at http://0.0.0.0:8000
  serving static dir: .

The interesting thing about light-server is that you can watch file changes and take action if there are any changes. In the following example, the js file and index.html under the current directory are monitored, and if there is a change, `` `npm run build``` is executed and the file is reloaded. (I used the example in the comment by hatappo. Thank you for your patience.)

JS file and index.Example of monitoring html


$ light-server -s -w "**/*.js, index.html # npm run build # reload"

Note that the character strings following the -w option are separated by #, and from the beginning, `monitored files` `,` `contents to be executed when changed` `,` `whether or not to reload ``. Please see the reference URL for details.

** Recommended **: Looking at the README of the official repository, I found that it supports HTTP2 (automatically supports HTTPS). In the following example, the certificate is automatically generated and then listens on the 4000 version port. Please be sure to access by HTTPS because you cannot access by HTTP.

Example of listening on HTTP2 on the 4000 version port


$ light-server -s . --http2
light-server is listening at https://0.0.0.0:4000
  serving static dir: .

Reference: light-server

nc command

The nc command is a tool for sending and receiving data from the command line using TCP and UDP. By using this command, it is possible to set up a simple Web server (I knew it for the first time after seeing tukiyo3's comment while saying that. Thank you for pointing out).

First of all, it is an execution method when the character string to be replied is specified in one liner. If you want to change the character string to be replied, change after \ n \ n. The following example returns "hello".

Example of listening on port 8000


$ while :; do { echo -e 'HTTP/1.1 200 OK\n\nhello'; } | nc -l 8000; done

If you want to reply the contents of the file, please execute as follows. The following example returns the contents of index.html.

When specifying the file to reply to


$ while :; do { echo -e 'HTTP/1.1 200 OK\n\n'; cat index.html; } | nc -l 8000; done

According to Reference 1, it was not possible to stop with Ctrl + C, but when I ran it on my MacOS X bash, I was able to stop it (for some reason I could not stop it when I ran it on zsh). If you want to make sure it stops, see the same article.

Reference 1: Simple HTTP server with nc command Reference 2: When you want to start a simple web server immediately

Recommended Posts

I tried collecting one-liner web servers
A collection of one-liner web servers
I tried to make a Web API
I tried benchmarking a web application framework
I tried scraping
I tried AutoKeras
I tried papermill
I tried django-slack
I tried Django
I tried spleeter
I tried cgo
I tried web scraping to analyze the lyrics.
I tried web scraping using python and selenium
I tried using parameterized
I tried using mimesis
I tried using anytree
I tried competitive programming
I tried running pymc
I tried ARP spoofing
I tried using aiomysql
I tried using Summpy
I tried Python> autopep8
I tried using coturn
I tried using Pipenv
I tried using matplotlib
I tried using "Anvil".
I tried using Hubot
I tried using ESPCN
I tried PyCaret2.0 (pycaret-nightly)
I tried using openpyxl
I tried deep learning
I tried AWS CDK!
I tried using Ipython
I tried to debug.
I tried using PyCaret
I tried using cron
I tried Kivy's mapview
I tried using ngrok
I tried using face_recognition
I tried to paste
I tried using Jupyter
I tried collecting data from a website with Scrapy
I tried moving EfficientDet
I tried shell programming
I tried using Heapq
I tried using doctest
I tried Python> decorator
I tried running TensorFlow
I tried Auto Gluon
I tried using folium
I tried using jinja2
I tried AWS Iot
I tried Bayesian optimization!
I tried using folium
I tried using time-window
I tried to get Web information using "Requests" and "lxml"
I tried connecting Raspberry Pi and conect + with Web API
[Python] I tried collecting data using the API of wikipedia
I tried Value Iteration Networks
I tried fp-growth with python
I tried scraping with Python