Skip to content

Commit 580b7f6

Browse files
committed
Improve cli output pipeline and error handling
1 parent d34931e commit 580b7f6

File tree

3 files changed

+33
-23
lines changed

3 files changed

+33
-23
lines changed

bin/cli.js

Lines changed: 28 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
#!/usr/bin/env node
22
var fs = require('fs');
3+
var path = require('path');
34
var parse = require('../');
5+
var stringify = require('JSONStream').stringify;
46
var args = require('nomnom')
57
.option('output', {
68
abbr: 'o',
@@ -40,28 +42,32 @@ if (!args.file) {
4042
});
4143
}
4244

45+
var output;
46+
if (args.output) {
47+
output = fs.createWriteStream(args.output)
48+
.on('error', function(err) {
49+
if (err.code === 'ENOENT') {
50+
var dir = path.dirname(args.output);
51+
console.error('No such directory: %s', dir);
52+
process.exit(1);
53+
return;
54+
}
55+
throw err;
56+
});
57+
} else {
58+
output = process.stdout
59+
.on('error', function (err) {
60+
if (process.stdout.isTTY) {
61+
// Only throw output errors if we're in
62+
// a TTY to prevent noise when piping
63+
// the output to other commands
64+
throw err;
65+
}
66+
});
67+
}
68+
4369
var parser = parse();
4470
input
4571
.pipe(parser)
46-
.on('data', function(data) {
47-
var str = JSON.stringify(data);
48-
if (args.output) {
49-
fs.createWriteStream(args.output)
50-
.on('error', function(err) {
51-
throw err;
52-
})
53-
.end(str, 'utf8');
54-
} else {
55-
process.stdout.write(str);
56-
}
57-
})
58-
.on('end', function () {
59-
if (!process.stdout.isTTY) {
60-
// Prevent noise if the command you're
61-
// piping the output to fails
62-
process.exit(0);
63-
}
64-
})
65-
.on('error', function (err) {
66-
throw err;
67-
});
72+
.pipe(stringify(false))
73+
.pipe(output);

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
},
2828
"homepage": "https://github.com/CMTegner/jsonml-parse",
2929
"dependencies": {
30+
"JSONStream": "^0.8.4",
3031
"htmlparser2": "^3.7.3",
3132
"lodash.isempty": "^2.4.1",
3233
"nomnom": "^1.8.0"

test/cli.sh

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,4 +9,7 @@ rm ${base}/cli/tmp.json
99
set +e
1010
error=$(node ${base}/../bin/cli.js nope 2>&1)
1111
test $? -eq 1
12-
[ "$error" = "No such file: nope" ] || (echo "'No such file' logic is broken!"; exit 1)
12+
[ "$error" = "No such file: nope" ] || (echo "'No such file' logic is broken!"; exit 1)
13+
error=$(node ${base}/../bin/cli.js ${base}/cli/markup.html -o /nope/nope/nope 2>&1)
14+
test $? -eq 1
15+
[ "$error" = "No such directory: /nope/nope" ] || (echo "'No such output directory' logic is broken!"; exit 1)

0 commit comments

Comments
 (0)