Post your best Lua script examples here

User avatar
By NopItTwice
#65469 I started to work on a new more intuitive HTTP server library for NodeMCU this weekend.
It behaves a lot like Express.js which many of you may know from Node.js.

It's extremely easy to use and very light-weight.
New functionality can easily be added through so called "middlewares".
You can find it on github: NodeMCU-Express

Let me give you a few examples:

To use the library, you start your script with:
Code: Select allrequire('HttpServer')

local app = express.new()
app:listen()

Then you can do as many of these as you'd like:

Code: Select all-- Register a new middleware that prints the url of every request
app:use(function(req,res,next)
    print(req.url)
    next()
end)

-- Register a new route that just returns an html site that says "HELLO WORLD!"
app:get('/helloworld',function(req,res)
    res:send('<html><head></head><body>HELLO WORLD!</body></html>')
end)

-- Register a new route at `/led-on` that turns an LED on
app:get('/led-on',function(req,res)
    gpio.write(4, gpio.HIGH) -- set GPIO 2 to HIGH
    res:send('Led turned on!')
end)

-- Serve the file `home.html` when visiting `/home`
app:use('/home',express.static('home.html'))

-- Serve all files that are in the folder `http` at url `/libs/...`
-- (To be more accurate I'm talking about all files starting with `http/`.)
app:use('/libs',express.static('http'))


For a full example that can be flashed as is go here: example.lua