diff --git a/bin/sql-formatter-cli.cjs b/bin/sql-formatter-cli.cjs index 358f7d59cf..c2940f4f42 100755 --- a/bin/sql-formatter-cli.cjs +++ b/bin/sql-formatter-cli.cjs @@ -7,6 +7,7 @@ const fs = require('fs'); const tty = require('tty'); const { version } = require('../package.json'); const { ArgumentParser } = require('argparse'); +const { promisify } = require('util'); class PrettierSQLArgs { constructor() { @@ -14,9 +15,28 @@ class PrettierSQLArgs { this.args = this.parser.parse_args(); this.cfg = this.readConfig(); - this.query = this.getInput(); - const formattedQuery = format(this.query, this.cfg).trim() + '\n'; - this.writeOutput(this.getOutputFile(this.args), formattedQuery); + this.readFile = promisify(fs.readFile); + this.getInput().then(input => { + this.query = input; + const formattedQuery = format(this.query, this.cfg).trim() + '\n'; + this.writeOutput(this.getOutputFile(this.args), formattedQuery); + }); + } + + async getStdin() { + if (process.stdin.isTTY) { + return Buffer.alloc(0); + } + + const result = []; + let length = 0; + + for await (const chunk of process.stdin) { + result.push(chunk); + length += chunk.length; + } + + return Buffer.concat(result, length).toString(); } getParser() { @@ -91,22 +111,26 @@ class PrettierSQLArgs { }; } - getInput() { + async getInput() { const infile = this.args.file || process.stdin.fd; - try { - return fs.readFileSync(infile, 'utf-8'); - } catch (e) { - if (e.code === 'EAGAIN') { - console.error('Error: no file specified and no data in stdin'); - process.exit(1); - } - if (e.code === 'ENOENT') { - console.error(`Error: could not open file ${infile}`); - process.exit(1); + if (this.args.file) { + try { + return await this.readFile(infile, { encoding: 'utf-8' }); + } catch (e) { + if (e.code === 'EAGAIN') { + console.error('Error: no file specified and no data in stdin'); + process.exit(1); + } + if (e.code === 'ENOENT') { + console.error(`Error: could not open file ${infile}`); + process.exit(1); + } + console.error('An unknown error has occurred, please file a bug report at:'); + console.log('https://github.com/sql-formatter-org/sql-formatter/issues\n'); + throw e; } - console.error('An unknown error has occurred, please file a bug report at:'); - console.log('https://github.com/sql-formatter-org/sql-formatter/issues\n'); - throw e; + } else { + return await this.getStdin(); } }