forked from uetchy/juno
/
jupyter.js
63 lines (55 loc) · 1.56 KB
/
jupyter.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
const { execSync, exec, spawn } = require('child_process')
const { relative } = require('path')
// Return a process pid which is listening specific port
function processListening(port) {
try {
const pid = execSync(`sleep 0.5 && lsof -ti TCP:${port} -s TCP:LISTEN`)
return String(pid)
} catch (err) {
return null
}
}
// Launch jupyter daemon and returns pid
function launchJupyter(command, rootPath, port) {
console.log('jupyter: launching')
const options = [rootPath, `--port=${port}`, '--no-browser']
const jupyter = spawn(command, options, { detached: true })
console.log(`pid: ${jupyter.pid}`)
if (jupyter.pid === undefined) {
return new Error('Jupyter wont started')
}
return null
}
// Open browser and show notebooks
function openBrowser(notebooks, rootPath, port) {
if (notebooks.length === 0) {
exec(`open "http://localhost:${port}"`)
} else {
notebooks.forEach(notebook => {
const target = relative(rootPath, notebook)
exec(`open "http://localhost:${port}/notebooks/${target}"`)
})
}
}
// Fetch or launch jupyter and returns their PID
function getJupyterProcess(command, rootPath, port) {
// Fetch existing process
let pid = processListening(port)
// Launch Jupyter if not existed
if (!pid) {
const err = launchJupyter(command, rootPath, port)
if (err) {
console.log('jupyter: something went wrong')
return null
}
console.log('jupyter: started')
while (!pid) {
pid = processListening(port)
}
}
return pid
}
module.exports = {
openBrowser,
getJupyterProcess,
}