n-riesco / ijavascript

IJavascript is a javascript kernel for the Jupyter notebook
Other
2.18k stars 187 forks source link

Comms usage? #100

Open gnestor opened 7 years ago

gnestor commented 7 years ago

Hi @n-riesco! I'm working on a proof-of-concept Javascript/Node.js widgets and I'm having trouble with comms on the Node.js side. Does ijavascript support comm messages? If so, how would you implement a basic connectToComm, comm.onMsg, and comm.send?

For reference, here is what I'm doing on the front-end using classic notebook:

Jupyter.notebook.kernel.comm_manager.register_target('test', (comm, msg) => {
  comm.on_msg(msg => {
    console.log(msg.content.data); 
  });
  comm.on_close(msg => { 
    console.log(msg); 
  });
  comm.send({'foo': 0});
});

And here is what I'm doing in Node.js using @jupyterlab/services:

import { XMLHttpRequest } from 'xmlhttprequest';
import { default as WebSocket } from 'ws';
import { KernelMessage, Kernel } from '@jupyterlab/services';

global.XMLHttpRequest = XMLHttpRequest;
global.WebSocket = WebSocket;

const BASE_URL = 'http://localhost:8888';
const TOKEN = /* your notebook session token */;

Kernel.listRunning({
    baseUrl: BASE_URL,
    token: TOKEN
}).then(kernelModels => {
  const model = kernelModels.find(model => model.name === 'babel');
  return Kernel.connectTo(model.id, {
    baseUrl: BASE_URL,
    token: TOKEN,
    name: model.name
  });
}).then(kernel => {
  const comm = kernel.connectToComm('test');
  comm.open({foo: 1});
  comm.onMsg = msg => {
    console.log(msg.content.data);
  };
  comm.onClose = msg => {
    console.log(msg);
  };
}).catch(error => {
  console.log(error);
});
n-riesco commented 7 years ago

I haven't implemented comms_* messages either.

The implementation could be similar to what I've discussed here.

We would need to provide an API for the user. I guess that we could just reproduce the API you've shown above:

var comm = $$.connectToComm('test');
comm.open({foo: 1});
comm.onMsg = console.log;
ghost commented 7 years ago

Any update on this? How do I do this from ijavascript? https://stackoverflow.com/questions/42773092/javascript-jupyter-notebook-how-to-get-code-cell-content

n-riesco commented 7 years ago

@megamindbrian I'm not sure the question in stackoverflow refers to comm_* messages. Could you open a new issue and give an example of you'd like to do in IJavascript?