-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdetechtiveMain.js
executable file
·79 lines (55 loc) · 1.91 KB
/
detechtiveMain.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
70
71
72
73
74
75
76
77
78
79
#!/usr/bin/env node
'use strict';
/**
* @module detechtiveMain
*/
/* A standalone utility. Reads an array of timelines from json file specified in the first command line argument.
* Attempts to merge the timelines. Prints modified timelines to standard output.
*/
var detechtive = require("./js/detechtive")
var fs = require('fs')
// Only use this in a standalone app, not in a module
process.on('uncaughtException', function(err) {
console.log(err.message)
if (err.showStackTrace !== false)
console.log(err.stack)
const ERROR = 1
process.exit(ERROR)
})
// TODO print output, error when file not found,
// First command line argument is path to nodejs, second is path to js file being executed, followed by
// application-specific arguments
var argv = process.argv
var filename = argv[2] || ""
const USAGE = "usage: detective [file]"
// Is file name omitted or incorrect?
if (filename.length === 0 || filename[0] === '-') {
const error = new Error(USAGE)
error.showStackTrace = false
throw error
}
// TODO: this loads the whole json file into memory at once. Use stream instead.
fs.readFile(filename, 'utf8', (err, contents) => {
// TODO better error handling for most common errors: file not found, no access privilege, etc.
if (err) {
err.showStackTrace = false
throw err
}
var timelines = JSON.parse(contents)
var mergedTimelines = detechtive.merge(timelines)
console.log(toString(mergedTimelines))
})
// TODO what if it's very long?
/**
* Convert timelines to string. TODO: can be too big, use stream instead
* @param timelines
* @returns {string}
*/
function toString(timelines) {
// Could just JSON.stringify() the entire timelines object, but it would be harder to get whitespaces right.
var result = "[\n"
for (var timeline of timelines)
result += JSON.stringify(timeline) + "\n"
result += "]"
return result
}