Skip to content

Commit

Permalink
Only wait for stdin for a little bit
Browse files Browse the repository at this point in the history
For this module, we only really care about stdin that is written right away, like when the process is piped.

This has the benefit of letting us easily add a fallback when there's no stdin.

Fixes #13
  • Loading branch information
sindresorhus committed Dec 2, 2016
1 parent c12aca8 commit e122e41
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 5 deletions.
17 changes: 17 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,17 @@ module.exports = () => {
return;
}

const timeout = setTimeout(() => {
resolve(ret);
}, 100);

stdin.unref();
stdin.setEncoding('utf8');

stdin.on('readable', () => {
clearTimeout(timeout);
stdin.ref();

let chunk;

while ((chunk = stdin.read())) {
Expand All @@ -36,7 +44,16 @@ module.exports.buffer = () => {
return;
}

const timeout = setTimeout(() => {
resolve(new Buffer(''));
}, 100);

stdin.unref();

stdin.on('readable', () => {
clearTimeout(timeout);
stdin.ref();

let chunk;

while ((chunk = stdin.read())) {
Expand Down
17 changes: 12 additions & 5 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

> Get [stdin](https://nodejs.org/api/process.html#process_process_stdin) as a string or buffer
This module expects stdin to be written right away. It's not intended for stdin being written at some arbitrary time.


## Install

Expand All @@ -16,21 +18,26 @@ $ npm install --save get-stdin
// example.js
const getStdin = require('get-stdin');

getStdin().then(str => {
console.log(str);
//=> 'unicorns'
getStdin().then(stdin => {
if (stdin.length > 0) {
console.log('stdin:', str);
} else {
console.log('input:', process.argv[2]);
}
});
```

```
$ echo unicorns | node example.js
unicorns
stdin: unicorns
$ node example.js unicorns
input: unicorns
```


## API

Both methods returns a promise that is resolved when the `end` event fires on the `stdin` stream, indicating that there is no more data to be read.
Both methods returns a promise that is resolved when the `end` event fires on the `stdin` stream or after 100ms, indicating that there is no more data to be read.

### getStdin()

Expand Down

0 comments on commit e122e41

Please sign in to comment.