2022年6月13日 星期一

[koa, root] How to serve entire folder using Koa

 How to serve entire folder using Koa?

井民全, jing, mqjing@gmail.com

Github: source


1. Setup

Step 1: Install Node JS and KOA server

curl -L https://git.io/n-install | bash -s -- -y   # install node js

npm install koa  # install koa server

npm install koa-static


// test file

File: test.js

const Koa = require('koa');

const app = new Koa();


// response

app.use(ctx => {

  ctx.body = 'Hello Koa';

});


app.listen(3000);



// run test

node test.js  // on server site to run this command

Open http://192.168.1.108:3000/    // on client site to run this command


Step 2: Put your static html

  1. Create server.js for koa server

File: ./webserver.js

const serve = require('koa-static')

const Koa = require('koa');

const path = require('path')


const app = new Koa();


// app.use(serve('./public')); 

app.use(serve(path.join(__dirname, '/public')))   # setup the root directory


app.listen(3000);

  1. Put your public stuff in ./public folder

File: ./public/index.htm

<!doctype html>

<html lang="en">


<head>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.min.js" type="text/javascript"></script>

</head>


<body>

    <h1>Test</h1>

    <script src="index.js"></script>

</body>

</html>

File: ./public/index.js

let body = document.getElementsByTagName("body")[0];


function createHtmlElement(strStyle, strTitle, funClickCallback){

    let ele = document.createElement(strStyle);

    if(strTitle != null)

      ele.innerHTML = strTitle;

    if (funClickCallback != null)

      ele.addEventListener('click', funClickCallback);

    return ele;

  }


function createHtmlButton(strTitle, funClickCallback, body){

    let ele = createHtmlElement('button', strTitle, funClickCallback);

    if(body == null){

      console.log('Error: createHtmlButton::body == null')

      return null;

    }


    body.appendChild(ele);

    return ele;

  }


function cbClickOK(){

      console.log('cbConnect::start to connect and send message');

}


function main(){

    createHtmlButton('OK', cbClickOK, body);

}



2. Run

Start server

node webserver.js

Start client

Open http://192.168.1.108:3000


Result