| 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 |
34×
1×
1×
1×
1×
1×
1×
4×
3×
3×
4×
3×
3×
2×
1×
1×
8×
8×
6×
1×
5×
1×
3×
1×
1×
1×
7×
1×
6×
1×
1×
1×
3×
3×
3×
3×
6×
6×
6×
5×
5×
1×
3×
2×
34×
| 'use strict'
var fs = require('fs')
, byline = require('byline')
, prompt = require('prompt')
// , process = require('process')
function promptAdmin(cb) {
var schema = {
properties: {
user: {
description: 'username',
message: 'username is required',
required: true
},
pass: {
description: 'password',
message: 'password is required',
required: true,
hidden: true
}
}
}
console.log('enter admin credentials')
prompt.start()
prompt.get(schema, cb)
}
function getAuth(admin, cb) {
if ( !cb ) {
cb = admin
admin = null
}
if ( admin ) return promptAdmin(cb)
getConfig(function (err, data) {
if (err) return cb(err)
if ( !data.token ) return cb(new Error('no token'))
cb(null, data.token)
})
}
function readJson(path, cb) {
fs.readFile(path, 'utf8', function (err, data) {
if (err) return cb(err)
try { var json = JSON.parse(data) }
catch (err) { return cb(err) }
cb(null, json)
})
}
function formatJson(data) {
return JSON.stringify(data, null, 2) + '\n'
}
function writeJson(path, data, cb) {
fs.writeFile(path, formatJson(data), cb)
}
function getUserHome() {
return process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE
}
function getConfig(cb) {
// TODO: store as props/INI instead of JSON ?
readJson( getUserHome() + '/.mlpmrc', cb )
}
function saveConfig(data, cb) {
// TODO: store as props/INI instead of JSON ?
writeJson( getUserHome() + '/.mlpmrc', data, cb )
}
function readByLine(filePath, cb, end) {
var fileStream = fs.createReadStream(filePath, { encoding: 'utf-8' })
var lineStream = byline.createStream(fileStream)
var resumed = true
lineStream.on('data', function(line) {
lineStream.pause()
resumed = false
cb(line.toString(),
function() {
lineStream.resume()
resumed = true
},
function() {
// TODO: backwards compat?
// if ( fileStream.destroy ) return fileStream.destroy()
fileStream.unpipe()
})
})
lineStream.on('end', function() {
Eif (resumed && end) return end()
})
}
module.exports = {
getAuth: getAuth,
readJson: readJson,
formatJson: formatJson,
writeJson: writeJson,
getConfig: getConfig,
saveConfig: saveConfig,
readByLine: readByLine
}
|