forked from choonkeat/elm-auto-encoder-decoder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
executable file
·69 lines (60 loc) · 2.37 KB
/
index.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
64
65
66
67
68
69
#!/usr/bin/env node
const fs = require('fs')
const path = require('path')
global.XMLHttpRequest = {}
const { Elm } = require('./build/Main.js')
const app = Elm.Main.init({ flags: {} })
const watching = (process.env.WATCHING !== 'false')
// optional configs
const extraImport = process.env.EXTRA_IMPORT
const generatedSrc = process.env.GENERATED_SRC
var throttle = {}
const autoModules = process.argv.slice(2).map((filepath) => innerPath(filepath, []).split(path.sep).join('.'))
var exitCount = autoModules.length
if (app.ports.exit && !watching) app.ports.exit.subscribe(function(i) {
exitCount--;
if (exitCount > 0 && i === 0) return // wait for more
process.exit(i)
})
if (app.ports.writeFile) {
app.ports.writeFile.subscribe(({ filename, encoding, data }) => {
if (generatedSrc) {
filename = path.join(generatedSrc, innerPath(filename, []) + path.extname(filename))
}
fs.mkdir(path.dirname(filename), { recursive: true }, function (err) {
if (err) return app.ports.onFileWritten.send({ filename, encoding, err })
fs.writeFile(filename, data, { encoding: encoding }, (err) => {
app.ports.onFileWritten.send({ filename, encoding, err })
})
})
})
}
function readAndWrite (filename, encoding, autoModules) {
throttle[filename] = (new Date()).getTime() // lock to throttle
fs.readFile(filename, { encoding: encoding }, (err, data) => {
app.ports.onFileContent.send({ filename, encoding, extraImport, autoModules, err, data })
setTimeout(function () { delete throttle[filename] }, 2000) // remove throttle after 2 seconds
})
}
function innerPath(filepath, resultpath) {
const parts = path.parse(filepath)
if ((!parts.name) || parts.name === 'src' || parts.name.endsWith('-src')) {
return resultpath.join(path.sep)
}
return innerPath(parts.dir, [parts.name, ...resultpath])
}
process.argv.slice(2).forEach((filepath) => {
var encoding = 'utf8'
fs.stat(filepath, function (err, stats) {
if (err) throw err
readAndWrite(filepath, 'utf8', autoModules)
if (!watching) return // the end
console.log('watching', filepath, '...')
var dirname = stats.isDirectory() ? filepath : path.dirname(filepath)
fs.watch(filepath, (eventType, basename) => {
var filename = path.join(dirname, basename)
if (throttle[filename]) return
readAndWrite(filename, encoding, autoModules)
})
})
})