专栏名称: zhongzhong05
码农
目录
相关文章推荐
中国城市规划  ·  5·30 ... ·  昨天  
51好读  ›  专栏  ›  zhongzhong05

Nexus.js介绍:一个多线程的JavaScript运行库

zhongzhong05  · 掘金  ·  · 2017-12-18 02:43

正文

请到「今天看啥」查看全文


  const startTime = Date.now();
  try {
    const device = new Nexus.IO.FilePushDevice('enwik8');
    const stream = new Nexus.IO.ReadableStream(device);

    stream.pushFilter(new Nexus.IO.EncodingConversionFilter("UTF-8", "UTF-16LE"));

    const wstreams = [0,1,2,3]
      .map(i => new Nexus.IO.WritableStream(new Nexus.IO.FileSinkDevice('enwik16-' + i)));

    console.log('piping...');

    stream.pipe(...wstreams);

    console.log('streaming...');

    await stream.resume();

    await stream.close();

    await Promise.all(wstreams.map(stream => stream.close()));

    console.log(`finished in ${(Date.now() * startTime) / 1000} seconds!`);
  } catch (e) {
    console.error('An error occurred: ', e);
  }
}

start().catch(console.error);

TCP/UDP

  • Nexus.js提供了一个Acceptor类,负责绑定ip地址/端口和监听连接
  • 每次收到一个连接请求,connection事件就会被触发,并且提供一个Socket设备。
  • 每一个Socket实例是全双工的I/O设备。
  • 你可以使用ReadableStream和WritableStream来操作Socket。

最基础的例子:(向客户端发送“Hello World”)

const acceptor = new Nexus.Net.TCP.Acceptor();
let count = 0;

acceptor.on('connection', (socket, endpoint) => {
  const connId = count++;
  console.log(`connection #${connId} from ${endpoint.address}:${endpoint.port}`);
  const rstream = new Nexus.IO.ReadableStream(socket);
  const wstream = new Nexus.IO.WritableStream(socket);
  const buffer = new Uint8Array(13);
  const message = 'Hello World!\n';
  for(let i = 0; i < 13; i++)
    buffer[i] = message.charCodeAt(i);
  rstream.pushFilter(new Nexus.IO.UTF8StringFilter());
  rstream.on('data', buffer => console.log(`got message: ${buffer}`));
  rstream.resume().catch(e => console.log(`client #${connId} at ${endpoint.address}:${endpoint.port} disconnected!`));
  console.log(`sending greeting to #${connId}!`);
  wstream.write(buffer);
});

acceptor.bind('127.0.0.1', 10000);
acceptor.listen();

console.log('server ready');

Http

  • Nexus提供了一个Nexus.Net.HTTP.Server类,该类基本上继承了TCPAcceptor
  • 一些基础接口
  • 当服务器端完成了对传入连接的基本的Http头的解析/校验时,将使用连接和同样的信息触发connection事件
  • 每一个连接实例都又一个request和一个response对象。这些是输入/输出设备。
  • 你可以构造ReadableStream和WritableStream来操纵request/response。
  • 如果你通过管道连接到一个Response对象,输入的流将会使用分块编码的模式。否者,你可以使用response.write()来写入一个常规的字符串。

复杂例子:(基本的Http服务器与块编码,细节省略)

....


/**
 * Creates an input stream from a path.
 * @param path
 * @returns {Promise<ReadableStream>}
 */
async function createInputStream(path) {
  if (path.startsWith('/')) // If it starts with '/', omit it.
    path = path.substr(1);
  if (path.startsWith('.')) // If it starts with '.', reject it.
    throw new






请到「今天看啥」查看全文