This is a very rough and verbose overview of an API that is simplistic and can be kept consistent across the entire code base. I visited many API possibilities that could have been used, and this API came out as the best combination of everything available.
First we'll start with examples from the file system API. This is a partial set of all features that already exist, also included are some new APIs.
Create a new file system object that can be operated on.
Return an array of all file resources that are open.
Return number of bytes read from all files since start of the applications.
Return number of bytes written to all files since start of the application.
Retrieve statistics about the file resource.
Open the file resource
Close the file resource.
Read data starting at byte position
for byte length
.
Write buffer
to file resource.
Return the number of bytes have been read from the file.
Return he number of bytes written to the file.
var myFile = new File('/path/to/my/file');
myFile.open('r+', function fileOpen(er) {
if (er)
throw er;
this.read(0, 16, fileRead);
});
function fileRead(er, data) {
if (er)
throw er;
console.log('Bytes read: ' + this.rx());
this.write(data, 0, data.length, fileWrite);
}
function fileWrite(er) {
if (er)
throw er;
console.log('Bytes written: ' + this.tx());
this.close(fileClose);
}
function fileClose(er) {
if (er)
throw er;
}
Create new TCP resource.
Return number of bytes read from all TCP connections.
Return number of bytes written to all TCP connections.
Bind to a port
and listen for incoming connections.
Connect to port
.
Call callback
if there's an error on the server.
When a connection is received byte the server call callback
.
When the server has been closed.
Flush the written data to the client. Data being written is automatically
queued during the synchronous write portion of the script, then written out
once when done. flush()
will automatically write data out to the client
immediately.
var server = new TCP();
server.onerror(onServerError);
server.onconnection(function onConnection(c) {
c.onerror(onConnectionError);
c.ondata(onData);
});
function onData() {
var data;
// The connection stream is automatically chunked mode.
while (data = this.read()) {
this.write(data);
}
this.end(onConnectionEnd);
}
function onConnectionEnd() {
console.log('Number of bytes read by connection: ' + this.rx());
console.log('Number of bytex written by connection: ' + this.tx());
this.server.close(onServerClose);
}
function onServerClose() {
console.log('Number of bytes read by server: ' + this.rx());
console.log('Number of bytes written by server: ' + this.tx());
console.log('Server has been closed');
}