forked from twilio/twilio-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
chore: refactor reading data from file or stdin (twilio#158)
- Loading branch information
childish-sambino
authored
Mar 18, 2020
1 parent
151e3cc
commit 66a8ac6
Showing
4 changed files
with
104 additions
and
112 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
const { TwilioCliError } = require('@twilio/cli-core').services.error; | ||
const { logger } = require('@twilio/cli-core').services.logging; | ||
const fs = require('fs'); | ||
const path = require('path'); | ||
|
||
async function readFileOrStdIn(filePath) { | ||
if (filePath) { | ||
return readFile(filePath); | ||
} | ||
|
||
const pipedInput = await readStream(); | ||
if (pipedInput) { | ||
return { | ||
filename: 'piped.txt', // placeholder filename for attachment | ||
content: pipedInput | ||
}; | ||
} | ||
} | ||
|
||
function readFile(filePath) { | ||
try { | ||
return { | ||
filename: path.basename(filePath), | ||
content: fs.readFileSync(filePath, 'base64') | ||
}; | ||
} catch (error) { | ||
logger.debug(error); | ||
throw new TwilioCliError('Unable to read the file: ' + filePath); | ||
} | ||
} | ||
|
||
async function readStream() { | ||
const input = await getStdin(); | ||
return Buffer.from(input).toString('base64'); | ||
} | ||
|
||
function getStdin() { | ||
return new Promise(resolve => { | ||
if (process.stdin.isTTY) { | ||
resolve(''); | ||
} else { | ||
process.stdin.setEncoding('utf8'); | ||
process.stdin.once('data', data => resolve(data)); | ||
} | ||
}); | ||
} | ||
|
||
module.exports = { | ||
readFileOrStdIn, | ||
readFile | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,4 +1,4 @@ | ||
require: test/helpers/init.js | ||
recursive: true | ||
reporter: spec | ||
timeout: 10000 | ||
timeout: false |
Oops, something went wrong.