npm / read Goto Github PK
View Code? Open in Web Editor NEWread(1) for node.
License: ISC License
read(1) for node.
License: ISC License
The idea is to implement an option to allow reading n characters rather than waiting for a new line character before executing callback, just like read(1)
has.
-n nchars
read returns after reading nchars characters rather
than waiting for a complete line of input.
@isaacs If you think this could be nice, I can dive by myself through the code and make a pull request.
Regards,
L.
On win7 with powershell and replace: true
will show the secret once a backspace is pressed.
A naive pass at this didn't work well.
Need to detach it completely and cleanly when finished.
Using this code, I still see the text output.
read({ prompt: 'Email: ', default: 'Email' }, (err, email) => {
read({ prompt: 'Password: ', default: 'Password', silent: true, replace: '*' }, (err, password) => {
resolve({email: email, password: password});
});
});
Just to confirm, I should see
Password: *****
when typing, right? Or does silent: true
simply not output the text a second time? Thanks.
current implementation is an async function, but the typescript types do not match this, ref: https://www.npmjs.com/package/@types/read
Type matches implementation
Using read
to prompt multiple times fails after the first line when:
setTimeout(f)
with f()
seems to "fix" the issue)x.js
const read = require("read")
const f = () => read({ prompt: ">" }, (e, line) => {
if (e) { throw e }
console.log("got:", line)
setTimeout(f)
})
f()
$ node x.js
> foo
got: foo
> bar
got: bar
> baz
got: baz
> ^D
$ node x.js <<< $'foo\nbar\nbaz'
> foo
got: foo
> $
I've replaced my use of read
with the following code, which has fewer features but works:
const _readline = require("readline")
const _rl_buf = []
const read_line = (prompt = null) =>
new Promise((resolve, reject) => {
const p = prompt || "", i = process.stdin, o = process.stdout
if (_rl_buf.length) {
if (p) { o.write(p) }
resolve(_rl_buf.shift())
return
}
const rl = _readline.createInterface({
input: i, output: o, prompt: p, terminal: false
})
let done = false
const f = (g, h = null) => {
if (!done) { done = true; rl.close(); g() }
else if (h) { h() }
}
rl.on("line" , line => f(() => resolve(line),
() => _rl_buf.push(line)))
rl.on("close" , () => f(() => resolve(null)))
rl.on("error" , e => f(() => reject(e)))
rl.prompt()
})
const f = () => read_line("> ").then(line => {
if (line == null) { return }
console.log("got:", line)
setTimeout(f)
})
f()
$ node y.js
> foo
got: foo
> bar
got: bar
> baz
got: baz
> $ node y.js <<< $'foo\nbar\nbaz'
> got: foo
> got: bar
> got: baz
> $
I use read for run app.js script, but I need that this script runs as background. Will be cool this feature.
types are broken
types are not broken
just npm i read and vscode shows wrong types when I hover read:
(alias) function read(options: Read.Options, callback: (error: any, result: string, isDefault: boolean) => any): void
(alias) namespace read
import read
No response
It would be nice to have some more usage samples, for example the ones you have in the tests.
Ideally, all possible options would be covered. Here's one that isn't covered (replace
):
const secret = await read({
prompt: "Insert secret value",
silent: true,
replace: "*"
});
safeStorage.save(secret);
Allows users to pre-calculate the length of the prompt without ANSI escape sequences, change:
https://github.com/isaacs/read/blob/master/lib/read.js#L50
To:
rl.setPrompt(prompt, opts.length || prompt.length);
Will submit a pull request if you are interested.
Despite passing terminal: false
, when readline.createInterface
is called, it is called with terminal: true
. It comes down to this line:
var terminal = !!(opts.terminal || output.isTTY)
I guess process.stdin
being TTY will set this to true, but I get some weird behavior with my prompts with this setting. Namely, there is a large set of extra space after my prompt text. This goes away if I can set terminal to false.
Is there just something simple I am missing or is this a bug? If it is a bug I can whip up a PR tomorrow. Let me know!
Hi, I noticed that there is a few console.error
messages in the test suite.
Writing to stderr duting tests is interpreted as a test failure by our automated test suite, can you please silence those ?
Thanks, Paolo
I used this module in one of my cli tools for accepting password input. One of my users tried to insert the password via the ol copy paste, and low and behold it did not work as expected.
I guess this would be resolved when readline
becomes baked in.
Reference: tim-smart/gista#5
After using the timeout function, I sometimes receive this error...
Here's my code:
read({ prompt: 'Connect?: y/n/q', timeout: 5000 , 'default': 'y'}, function(error, result, isDefault) {
process.stdin.destroy();
The Error that throws
tty.js:65
this._handle.setRawMode(flag);
^
TypeError: Cannot call method 'setRawMode' of null
at ReadStream.setRawMode (tty.js:65:16)
at Interface._setRawMode (readline.js:165:23)
at Interface.close (readline.js:268:10)
at done (/node_modules/read/lib/read.js:78:8)
at onError (/node_modules/read/lib/read.js:93:5)
at null._onTimeout (/node_modules/read/lib/read.js:72:7)
at Timer.listOnTimeout [as ontimeout] (timers.js:110:15)
The timeout works correctly but then I receive this error maybe a second after.
I'm using nodejs v0.10.12 and the latest module version from NPM.
I've been struggling with how to test stdin in a single process. In prompt I've been using a mock stream which I pass along to the prompt.
Thoughts?
A little similar to this issue: https://github.com/isaacs/read/issues/3
Deleting characters doesn't work well with replace, because the backspace control characters also get replaced.
Whats the best way to ask multiple questions? E.g.:
read({prompt: 'X?'}, function(err, x) {
read({prompt: 'Y?'}, function(err, y) {
read({prompt: 'K?'}, function(err, k) {
});
});
});
Reproduction:
const fs = require('fs')
const readCb = require('read')
async function read(opts) {
return new Promise((resolve, reject) => {
readCb(opts, (err, line) => {
resolve([err, line])
})
})
}
;(async () => {
const [err, password] = await read({ prompt: 'Password: ', silent: true })
console.log(password)
console.log(fs.readFileSync(0).toString())
})()
Run:
node --unhandled-rejections=strict main.js
Outcome:
fs.js:614
handleErrorFromBinding(ctx);
^
Error: EAGAIN: resource temporarily unavailable, read
at Object.readSync (fs.js:614:3)
at tryReadSync (fs.js:383:20)
at Object.readFileSync (fs.js:420:19)
at /home/ciro/test/main.js:70:18
at processTicksAndRejections (internal/process/task_queues.js:95:5) {
errno: -11,
syscall: 'read',
code: 'EAGAIN'
}
read 1.0.7, node.js v14.17.0., Ubuntu 21.10.
Related: https://stackoverflow.com/questions/4708787/get-password-from-input-using-node-js/71868483#71868483
Issue: We detected vulnerable dependencies in your project by using the command “npm audit”:
cryptiles <=4.1.1
Severity: high
Insufficient Entropy - https://npmjs.com/advisories/1464
Depends on vulnerable versions of boom
fix available via npm audit fix --force
Will install [email protected], which is a breaking change
node_modules/cryptiles
hawk 0.0.6 - 6.0.2
Depends on vulnerable versions of boom
Depends on vulnerable versions of cryptiles
Depends on vulnerable versions of hoek
Depends on vulnerable versions of sntp
node_modules/hawk
request 2.16.0 - 2.81.0
Depends on vulnerable versions of hawk
Depends on vulnerable versions of tunnel-agent
node_modules/request
coveralls <=2.13.3
Depends on vulnerable versions of js-yaml
Depends on vulnerable versions of minimist
Depends on vulnerable versions of request
node_modules/coveralls
tap 1.1.0 - 11.1.2 || 13.0.0-rc.0 - 13.0.0
Depends on vulnerable versions of coveralls
Depends on vulnerable versions of nyc
node_modules/tap
diff <3.5.0
Severity: high
Regular Expression Denial of Service - https://npmjs.com/advisories/1631
fix available via npm audit fix
node_modules/diff
tap-mocha-reporter 0.0.4 - 5.0.0
Depends on vulnerable versions of diff
node_modules/tap-mocha-reporter
hoek <=4.2.0 || 5.0.0 - 5.0.2
Severity: moderate
Prototype Pollution - https://npmjs.com/advisories/566
fix available via npm audit fix --force
Will install [email protected], which is a breaking change
node_modules/hoek
boom <=3.1.2
Depends on vulnerable versions of hoek
node_modules/boom
cryptiles <=4.1.1
Depends on vulnerable versions of boom
node_modules/cryptiles
hawk 0.0.6 - 6.0.2
Depends on vulnerable versions of boom
Depends on vulnerable versions of cryptiles
Depends on vulnerable versions of hoek
Depends on vulnerable versions of sntp
node_modules/hawk
request 2.16.0 - 2.81.0
Depends on vulnerable versions of hawk
Depends on vulnerable versions of tunnel-agent
node_modules/request
coveralls <=2.13.3
Depends on vulnerable versions of js-yaml
Depends on vulnerable versions of minimist
Depends on vulnerable versions of request
node_modules/coveralls
tap 1.1.0 - 11.1.2 || 13.0.0-rc.0 - 13.0.0
Depends on vulnerable versions of coveralls
Depends on vulnerable versions of nyc
node_modules/tap
sntp 0.0.0 || 0.1.1 - 2.0.0
Depends on vulnerable versions of hoek
node_modules/sntp
js-yaml <=3.13.0
Severity: high
Denial of Service - https://npmjs.com/advisories/788
Code Injection - https://npmjs.com/advisories/813
fix available via npm audit fix --force
Will install [email protected], which is a breaking change
node_modules/coveralls/node_modules/js-yaml
coveralls <=2.13.3
Depends on vulnerable versions of js-yaml
Depends on vulnerable versions of minimist
Depends on vulnerable versions of request
node_modules/coveralls
tap 1.1.0 - 11.1.2 || 13.0.0-rc.0 - 13.0.0
Depends on vulnerable versions of coveralls
Depends on vulnerable versions of nyc
node_modules/tap
lodash <=4.17.20
Severity: high
Prototype Pollution - https://npmjs.com/advisories/1065
Prototype Pollution - https://npmjs.com/advisories/1523
Command Injection - https://npmjs.com/advisories/1673
Prototype Pollution - https://npmjs.com/advisories/577
Prototype Pollution - https://npmjs.com/advisories/782
fix available via npm audit fix --force
Will install [email protected], which is a breaking change
node_modules/lodash
nyc <=5.0.1 || 6.2.0-alpha - 6.6.1
Depends on vulnerable versions of istanbul
Depends on vulnerable versions of lodash
node_modules/nyc
tap 1.1.0 - 11.1.2 || 13.0.0-rc.0 - 13.0.0
Depends on vulnerable versions of coveralls
Depends on vulnerable versions of nyc
node_modules/tap
minimatch <=3.0.1
Severity: high
Regular Expression Denial of Service - https://npmjs.com/advisories/118
fix available via npm audit fix --force
Will install [email protected], which is a breaking change
node_modules/fileset/node_modules/minimatch
fileset 0.1.0 - 0.2.1
Depends on vulnerable versions of minimatch
node_modules/fileset
istanbul <=0.4.4
Depends on vulnerable versions of fileset
node_modules/istanbul
nyc <=5.0.1 || 6.2.0-alpha - 6.6.1
Depends on vulnerable versions of istanbul
Depends on vulnerable versions of lodash
node_modules/nyc
tap 1.1.0 - 11.1.2 || 13.0.0-rc.0 - 13.0.0
Depends on vulnerable versions of coveralls
Depends on vulnerable versions of nyc
node_modules/tap
minimist <0.2.1 || >=1.0.0 <1.2.3
Prototype Pollution - https://npmjs.com/advisories/1179
fix available via npm audit fix --force
Will install [email protected], which is a breaking change
node_modules/minimist
coveralls <=2.13.3
Depends on vulnerable versions of js-yaml
Depends on vulnerable versions of minimist
Depends on vulnerable versions of request
node_modules/coveralls
tap 1.1.0 - 11.1.2 || 13.0.0-rc.0 - 13.0.0
Depends on vulnerable versions of coveralls
Depends on vulnerable versions of nyc
node_modules/tap
tunnel-agent <0.6.0
Severity: moderate
Memory Exposure - https://npmjs.com/advisories/598
fix available via npm audit fix --force
Will install [email protected], which is a breaking change
node_modules/tunnel-agent
request 2.16.0 - 2.81.0
Depends on vulnerable versions of hawk
Depends on vulnerable versions of tunnel-agent
node_modules/request
coveralls <=2.13.3
Depends on vulnerable versions of js-yaml
Depends on vulnerable versions of minimist
Depends on vulnerable versions of request
node_modules/coveralls
tap 1.1.0 - 11.1.2 || 13.0.0-rc.0 - 13.0.0
Depends on vulnerable versions of coveralls
Depends on vulnerable versions of nyc
node_modules/tap
18 vulnerabilities (1 low, 6 moderate, 11 high)
To address issues that do not require attention, run:
npm audit fix
To address all issues (including breaking changes), run:
npm audit fix --force
Questions: We are conducting a research study on vulnerable dependencies in open-source JS projects. We are curious:
For any publication or research report based on this study, we will share all responses from developers in an anonymous way. Both your projects and personal information will be kept confidential.
Description: Many popular NPM packages have been found vulnerable and may carry significant risks [1]. Developers are recommended to monitor and avoid the vulnerable versions of the library. The vulnerabilities have been identified and reported by other developers, and their descriptions are available in the npm registry [2].
Steps to reproduce:
Suggested Solution: Npm has introduced the “npm audit fix” command to fix the vulnerabilities. Execute the command to apply remediation to the dependency tree.
References:
2019. 10 npm Security Best Practices. https://snyk.io/blog/ten-npm-security-best-practices/.
2021. npm-audit. https://docs.npmjs.com/cli/v7/commands/npm-audit.
You still open to the idea of
{
stdin: new Stream(),
stdout: new stream()
}
as valid options to read(opts)
?
I cut a similar issue to the node-promptly module earlier: moxystudio/node-promptly#2
When the prompt contains colored/formatted text, the cursor is indented far to the right.
I skimmed through the code, and I think I see where the issue is:
https://github.com/isaacs/read/blob/master/lib/read.js#L56
Formatted strings end up with ANSI color codes are part of the string. Looking up the length property on them returns a misleading result. Would you accept a patch to strip ANSI codes before reading the length of the prompt?
Using nvm to run on a v0.11 of node.
shuan@OptimusRetina ~/Projects/javascript/watson-stream: node -v
v0.11.13
shuan@OptimusRetina ~/Projects/javascript/watson-stream: npm -v
1.4.9
shuan@OptimusRetina ~/Projects/javascript/watson-stream: npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sane defaults.
See `npm help json` for definitive documentation on these fields
and exactly what they do.
Use `npm install <pkg> --save` afterwards to install a package and
save it as a dependency in the package.json file.
Press ^C at any time to quit.
name: (watson-stream)
version: (0.0.0) 1.0.0
description:
entry point: (index.js)
test command:
git repository: https://github.com/swang/watson-stream
keywords: watson stream att
author: Shuan Wang
license: (ISC)
About to write to /Users/shuan/Projects/javascript/watson-stream/package.json:
{
"name": "watson-stream",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "https://github.com/swang/watson-stream"
},
"keywords": [
"watson",
"stream",
"att"
],
"author": "Shuan Wang",
"license": "ISC",
"bugs": {
"url": "https://github.com/swang/watson-stream/issues"
},
"homepage": "https://github.com/swang/watson-stream"
}
(node) warning: possible EventEmitter memory leak detected. 11 listeners added. Use emitter.setMaxListeners() to increase limit.
Trace
at ReadStream.EventEmitter.addListener (events.js:179:15)
at ReadStream.Readable.on (_stream_readable.js:667:33)
at new Interface (readline.js:124:11)
at Object.exports.createInterface (readline.js:38:10)
at read (/Users/shuan/.nvm/v0.11.13/lib/node_modules/npm/node_modules/read/lib/read.js:45:23)
at /Users/shuan/.nvm/v0.11.13/lib/node_modules/npm/node_modules/init-package-json/init-package-json.js:95:9
at final (/Users/shuan/.nvm/v0.11.13/lib/node_modules/npm/node_modules/read-package-json/read-json.js:349:17)
at then (/Users/shuan/.nvm/v0.11.13/lib/node_modules/npm/node_modules/read-package-json/read-json.js:126:33)
at /Users/shuan/.nvm/v0.11.13/lib/node_modules/npm/node_modules/read-package-json/read-json.js:316:48
at fs.js:228:20
Is this ok? (yes)
Hitting enter still generates the package.json file, this does not show up when running a 0.10 version of node.
TL;DR: The mute-stream module needs a quick fix: npm/mute-stream#5
I thought it might be a good idea to document how the above bug affects this module (and dependent modules like prompt). Calling read()
with a WriteStream other than process.stdout
as the output
option (see #5) winds up causing end()
to be called on the WriteStream instance. If you’re just doing a single prompt for user input this is no big deal, but subsequent prompts to the same WriteStream instance will not be shown to the user. The following code will reproduce the issue:
var read = require("read")
var tty = require("tty")
var fs = require("fs")
var ttyFD = fs.openSync("/dev/tty", "r+")
var ttyWS = new tty.WriteStream(ttyFD)
read({ output: ttyWS, prompt: "1st: " }, function (err, first) {
read({ output: ttyWS, prompt: "2nd: " }, function (err, second) {
console.log({ first: first, second: second })
})
})
The 1st:
prompt will be printed, but the 2nd:
prompt will not be, because ttyWS
got end
ed. Presumably this does not affect the default of process.stdout
because of some io.js magic that re-opens process.stdout
if there is an attempt to write to it when it has already been end
ed.
One workaround for users of the read module is to no-op the WriteStream instance’s end
method, like so:
ttyWS.end = function () {}
Ultimately, the culprit here is this bug in mute-stream: npm/mute-stream#5, which lets the end()
call pipe to the WriteStream instance. Fixing that and updating the dependency should fix this bug.
Thanks for taking a look at this!
@isaacs your package.json states this component is ISC-licensed. Yet you have two license files at the root:
Which one applies? both?
Thanks!
Hi, could you please publish the latest version on npm?
I only see 0.0.1
, 0.0.2
, 0.0.3
, 0.1.0
, 0.1.1
while flatiron
depends on prompt
that asks for 1.0.x
When using the options silent: true, replace: '*', then after input of the password and hitting return, an extra new line is displayed in the terminal. It is not the case when no replace option is set.
possible solution: this seems to be due to the line : read.js:101:
output.write('\r\n')
removing this line solves the problem, I wonder why it was there.
Here's my example:
read = require('read')
read { prompt: "Password: ", silent: true }, (error, password) ->
console.log(password)
When I enter a few characters, hit delete a few times and then reenter them, the resulting password contains all of the characters.
When I run the example.js
on my Windows 8 machine I can see my password even though silent
is set to true
. Haven't tested this on other Windows versions though.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.