diff --git a/index.js b/index.js index 527c67a..0c9bef5 100755 --- a/index.js +++ b/index.js @@ -5,6 +5,7 @@ const fs = require('node:fs'); const path = require('node:path'); const util = require("node:util"); const safeEval = require('safe-eval') +const { createInterface } = require("node:readline") const Options = { DISABLE_CUSTOM_METHODS: ["-m", "--disable-custom-methods", Boolean, "disable the usage of custom methods (prevents fields override)"], @@ -38,24 +39,37 @@ if (getOption(Options.VERSION)) { process.exit(0) } +// parse args const query = args._[0] let json = args._[1] || "" +// check query if (!query) throw Error("missing query argument") if (!query.startsWith(".") && !query.startsWith("[")) throw Error("query must start with either \".\" or \"[\"") +// normal usage if (json !== "") { - runJSJQ(query, json) - process.exit(0) -} + try { + runJSJQ(query, json); + } catch (err) { + console.error("JSJQ error:", err) + process.exit(1) + } -process.stdin.on('data', (data) => { - json += data.toString(); -}); -process.stdin.on('end', () => { - runJSJQ(query, json); -}); + process.exit(0) +}; + +// pipe usage +(async function () { + for await (const json of createInterface({ input: process.stdin })) { + try { + runJSJQ(query, json); + } catch (err) { + console.error("JSJQ error:", err) + } + } +})(); function runJSJQ(query, json) { const isJsonFile = isValidFilePath(json) @@ -91,7 +105,7 @@ function runJSJQ(query, json) { if (query === ".") { clearObject(OBJECT) print(OBJECT) - process.exit(0) + return } const code = `OBJECT${query};` diff --git a/test.sh b/test.sh index 671e0b6..bb46c18 100755 --- a/test.sh +++ b/test.sh @@ -15,6 +15,12 @@ check_test() { fi } +check_error_string() { + if [ "$1" != "" ]; then + errors+=("ERROR at \"$test\": \n\tunexpected error\n") + fi +} + check_test_error() { if [ $? -eq 0 ]; then errors+=("ERROR at \"$test\": \n\texpected exit with error\n") @@ -91,6 +97,15 @@ exp="[ 1, 2, 3 ]" res=$(echo '{ "data": [1, 2, 3] }' | node . '.data') check_test +test="from pipe multiple" +exp="[ 1, 2, 3 ]" +err=$(( + echo '{ "data": [1, 2, 3] }'; sleep 1; + echo '{ "data": [1, 2, 3] }'; sleep 1; + echo '{ "data": [1, 2, 3] }' +) | node . '.data' 2>&1 >/dev/null) +check_error_string "$err" + test="compact option" exp="[['a',1],['b',2],['c',3]]" res=$(node . '.data.listEntries()' '{ "data": {"a": 1, "b": 2, "c": 3} }' -c) @@ -116,7 +131,6 @@ exp="string" res=$(node . '.data' '{ "data": "string" }' --raw-output) check_test - if [ "${#errors[@]}" -ne "0" ]; then for err in "${errors[@]}"; do printf "$err\n"