Skip to content

Design Core Interface that wraps libuv #2

@creationix

Description

@creationix

This task is to design the interface that wraps libuv and exposes it to JavaScript. This should be as minimal as possible while still feeling like natural JavaScript and not C.

For example, in libuv, there is a hierarchy of structs that act like classes with inheritance. In JS, we can use prototype chains for the uv_tcp_t methods that inherits from uv_stream_t methods that inherits from uv_handle_t methods.

All libuv functions are plain C functions. There are no classes. The ones that act like methods accept the struct as the first argument. In luv, I exposed these in both ways.

For example, here is a sample TCP echo server in plain luv.

local uv = require('uv')

local server = uv.new_tcp()
server:bind("127.0.0.1", 1337)
server:listen(128, function (err)
  assert(not err, err)
  local client = uv.new_tcp()
  server:accept(client)
  client:read_start(function (err, chunk)
    assert(not err, err)
    if chunk then
      client:write(chunk)
    else
      client:shutdown()
      client:close()
    end
  end)
end)
print("TCP server listening at 127.0.0.1 port 1337")
uv.run()

In lua, there are no methods per-se, but the obj:name(...) syntax means to callobj.name(obj, ...) injecting the thing to the left of the colon as the first argument. In JS, we have this which can be used in a similar way.

var uv = require('uv');

var server = new uv.Tcp();
server.bind("127.0.0.1", 1337);
server.listen(128, function (err) {
  if (err) throw err;
  var client = new uv.Tcp();
  server.accept(client);
  client.read_start(function (err, chunk) {
    if (err) throw err;
    if (chunk) {
      client.write(chunk);
    }
    else {
      client.shutdown();
      client.close();
    }
  });
});
print("TCP server listening at 127.0.0.1 port 1337");
uv.run();

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions