/
get-input.js
47 lines (36 loc) · 1.08 KB
/
get-input.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
import {createReadStream} from "fs"
import path from "path"
import fs from "fs"
import {promisify} from "util"
async function checkPathIsRegularFile (path) {
return promisify(fs.stat)(path)
.then(stats => stats.isFile())
.catch(() => false)
}
async function getStream ({file, isTTY}) {
if (file != null && file != "-") {
let filepath = path.resolve(file)
if (!await checkPathIsRegularFile(filepath)) {
throw new Error(`not a file: "${filepath}"`)
}
return createReadStream(filepath)
}
let packageLockPath = "package-lock.json"
let packageLockExists = await checkPathIsRegularFile(packageLockPath)
if (!file && isTTY && packageLockExists) {
return createReadStream(packageLockPath)
}
return process.stdin
}
export default async function getInput ({file}) {
let {isTTY} = process.stdin
let stream = await getStream({file, isTTY})
stream.resume()
stream.setEncoding("utf-8")
let input = ""
stream.on("data", chunk => input += chunk)
return new Promise((keepPromise, breakPromise) => {
stream.on("end", () => keepPromise(input))
stream.on("error", breakPromise)
})
}