Faster than Node.js? Getting started with Luvit on OS X

Post to Twitter

Luvit is asynchronous I/O for Lua. If you’re familiar with Node.js then you might see similarities in the code I’ll show in this article. There is still some debate in the community but generally you’ll find that currently Luvit uses less memory than Node.js and runs just as fast or faster (this of course varies as each project is in active development and it depends on what your doing, how well written your code is, etc.). Today I’ll show you how to quickly setup and run a sample HTTP Server on OS X (Lion) as well as how to create a simple module using Luvit. I’ll be using Luvit version 0.5.0.


The first thing you’ll want to do is install Luvit. The easiest way is to just grab the binaries from here. Extract the files to somewhere convenient and you can then add the following to your path:

/Your-Install-Location/luvit/bin/

Create a file called demo.lua and put the following inside of it:

local http = require("http")

http.createServer(function (req, res)
  local body = "Hello world\n"
  res:writeHead(200, {
    ["Content-Type"] = "text/plain",
    ["Content-Length"] = #body
  })
  res:finish(body)
end):listen(8080)

print("Server listening at http://localhost:8080/")

Save the file and then from the terminal go to the location where the demo.lua file was saved and run the following:

$ ./luvit demo.lua

The output should be:

Server listening at http://localhost:8080/

Open a web browser to this link to see the results.

Let’s try another example that uses a module which I’ll borrow from here. Create two new files. Name the first file hello.lua and the other run.lua.

Here is the code for the module, hello.lua:

local hello = {}
hello.world = function()
  print("Hello World")
end
return hello

Now we can add the code for run.lua:

local hello = require('./hello')
hello.world()

Save both of these files in the same folder and then run the example like this:

$ ./luvit run.lua

Expected output:

Hello World

Keep in mind if your coming from the Node.js world then there are currently a lot fewer libraries/modules/projects supporting Luvit. More are showing up everyday but you’ll find NPM has much more in it right now. If your looking for a Luvit package manager you can check lum out.

Post to Twitter

This entry was posted in Luvit, Open Source. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>