Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
180 lines (158 loc) · 6.01 KB
/
Copy pathserver.js
File metadata and controls
180 lines (158 loc) · 6.01 KB
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
const htmlInject = require('./src/htmlInject')
const http = require('http')
const path = require('path')
const connect = require('connect')
const serveStatic = require('serve-static')
const bodyParser = require('body-parser')
const compression = require('compression')
const WebSocket = require('ws')
const chokidar = require('chokidar')
const chalk = require('chalk')
const mkdirp = require('mkdirp')
const fs = require('fs')
const PORT = process.env.PORT || 7897
const WS_PORT = process.env.WS_PORT || 7898
const NOTEBOOKS_DIR = process.env.NOTEBOOKS_DIR || './notebooks'
const VIEWS_DIR = process.env.VIEWS_DIR || './notebook-views'
const PUBLIC_DIR = process.env.PUBLIC_DIR || null
const FORCE = process.env.FORCE === 'true' || process.env.FORCE === true ? true : false
if (FORCE) {
console.log(chalk.blue(`Creating directory "${path.resolve(NOTEBOOKS_DIR)}"`))
console.log(chalk.blue(`Creating directory "${path.resolve(VIEWS_DIR)}"`))
mkdirp.sync(NOTEBOOKS_DIR)
mkdirp.sync(VIEWS_DIR)
}
if (!fs.existsSync(NOTEBOOKS_DIR)) {
console.error(
chalk.bold.red(`
Directory "${path.resolve(NOTEBOOKS_DIR)}" doesn't exist.
`) + chalk.bold.blue(`
Run with -f (--force) to have the directories created for you. For more info, run \`observable-local --help\`
`))
process.exit(1)
}
const app = connect()
app.use(compression())
// serve dist directory as static files
app.use(serveStatic(appPath('./dist' ), { fallthrough: true }))
// route that serves an html that loads a notebook and opens a websocket to recieve change events
app.use('/run', (req, res) => {
// See if there's a named html view for this notebook. If so, to serve instead of the default html
// Expected name is the notebook's name UNLESS explicitly specified in query (?view=aview.html)
const htmlViewName = (req.url.match(/[?&]view=([^&]*)/i) && RegExp.$1) || req.url.replace(/^\/|\/$/g, '')
let htmlView = path.resolve(`${VIEWS_DIR}/${htmlViewName}.html`)
if(!fs.existsSync(htmlView)) {
htmlView = appPath('./src/index.html')
}
res.setHeader('Content-Type', 'text/html')
res.end(
htmlInject(fs.readFileSync(htmlView, 'utf8'), {
head: `<link rel='stylesheet' href='/observable-local.css'>`,
body: `<script type='text/javascript' src='/observable-local.js'></script>`,
})
)
})
// serve notebooks directory listing as json
app.use('/notebooks', function(req, res, next) {
if (req.url === '/') {
res.setHeader('Content-Type', 'application/json')
fs.readdir(NOTEBOOKS_DIR, (err, listing) => {
if (err) {
console.log(chalk.red(err))
} else {
res.end(JSON.stringify(listing))
}
})
} else {
next()
}
})
// serve notebooks as static files
app.use('/notebooks', serveStatic(NOTEBOOKS_DIR))
if (!fs.existsSync(VIEWS_DIR)) {
console.log(chalk.blue(`
The directory "${VIEWS_DIR}" doesn't exist.
Any view changes you make (e.g. turning on/off cells) will not persist.
For more info, run \`observable-local --help\`
`))
} else {
// serve views as static files and accept POST overwrites
app.use(bodyParser.json())
app.use('/notebook-views', function(req, res, next) {
if (req.method === 'POST') {
console.log(chalk.blue(`Saving notebook view state "${VIEWS_DIR + req.url}"`))
fs.writeFileSync(
VIEWS_DIR + req.url,
JSON.stringify(req.body, null, ' '),
'utf8'
)
res.end('{}')
} else {
next()
}
})
app.use('/notebook-views', serveStatic(VIEWS_DIR))
}
if (PUBLIC_DIR && fs.existsSync(PUBLIC_DIR)) {
// serve static files from a user-specified public directory
console.log(chalk.blue(`Serving "${path.resolve(PUBLIC_DIR)}" as static directory`))
app.use('/', serveStatic(PUBLIC_DIR))
}
app.use('/socket', function(req, res, next) {
res.end(`ws://${req.headers.host.split(':')[0]}:${WS_PORT}`)
})
const wss = new WebSocket.Server({ port: WS_PORT })
wss.on('connection', function connection(ws) {
ws.on('error', function(e) {
if (e.code !== 'ECONNRESET') {
console.error(e)
}
})
})
// Broadcasts to all connected clients.
wss.broadcast = function(data) {
wss.clients.forEach(function each(client) {
if (client.readyState === WebSocket.OPEN) {
client.send(data)
}
})
}
// Watch for file changes and broadcast them via websocket
var watcher = chokidar.watch(NOTEBOOKS_DIR).on('change', (filepath, meta) => {
const accessTime = meta && meta.atime && meta.atime.getTime()
const modifyTime = meta && meta.mtime && meta.mtime.getTime()
// In certain cases (specifically on Windows and possibly only when
// files are on a network drive), Chokidar triggers events even if the
// file was simply accessed (as opposed to modified), which in-turn
// can create infinite update loops. To avoid this, we compare timestamps
// and only proceed if modifiedTime is as recent as accessTime
if (accessTime > modifyTime) { return }
console.log(chalk.blue(`Change detected in "${filepath}"`))
const filename = path.basename(filepath)
wss.broadcast(
JSON.stringify({
event: 'update',
filename: filename.replace(path.extname(filename), '')
})
)
})
let suggestedNotebook = 'welcome-notebook.js'
const existingNotebooks = fs.readdirSync(NOTEBOOKS_DIR).filter(name => (/\.js$/).test(name))
if (existingNotebooks.length === 0) {
fs.createReadStream(appPath(`./notebooks/${suggestedNotebook}`))
.pipe(fs.createWriteStream(`./${NOTEBOOKS_DIR}/${suggestedNotebook}`))
fs.createReadStream(appPath(`./notebook-views/${suggestedNotebook}on`))
.pipe(fs.createWriteStream(`./${VIEWS_DIR}/${suggestedNotebook}on`))
} else if (existingNotebooks.indexOf(suggestedNotebook) == -1) {
// pick a random notebook
suggestedNotebook = existingNotebooks[Math.floor(Math.random() * existingNotebooks.length)]
}
const suggestedUrl = `http://localhost:${PORT}/run/${suggestedNotebook.replace(/\.js$/, '')}`
console.log(`
Server listening on port ${PORT}
Try visiting ${chalk.bold.underline(suggestedUrl)}
`)
http.createServer(app).listen(PORT)
function appPath(relative) {
return path.resolve(__dirname, relative)
}