or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/npm-read

Enhanced Node.js utility for reading user input from stdin with features like silent mode, timeouts, and defaults

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/read@4.1.x

To install, run

npx @tessl/cli install tessl/npm-read@4.1.0

0

# read

1

2

Enhanced Node.js utility for reading user input from stdin with features like silent mode, timeouts, defaults, and autocomplete. Similar to readline's question() method but with additional functionality for CLI applications.

3

4

## Package Information

5

6

- **Package Name**: read

7

- **Package Type**: npm

8

- **Language**: TypeScript

9

- **Installation**: `npm install read`

10

11

## Core Imports

12

13

```typescript

14

import { read, Options } from "read";

15

```

16

17

For CommonJS:

18

19

```javascript

20

const { read } = require("read");

21

```

22

23

## Basic Usage

24

25

```typescript

26

import { read } from "read";

27

28

// Simple input

29

const name = await read({ prompt: "Name: " });

30

31

// Input with default value

32

const email = await read({

33

prompt: "Email: ",

34

default: "user@example.com"

35

});

36

37

// Silent input for passwords

38

const password = await read({

39

prompt: "Password: ",

40

silent: true

41

});

42

43

// Input with timeout

44

try {

45

const response = await read({

46

prompt: "Quick response: ",

47

timeout: 5000

48

});

49

} catch (err) {

50

console.log("Timed out!");

51

}

52

```

53

54

## Capabilities

55

56

### Main Read Function

57

58

Reads user input from stdin with comprehensive configuration options.

59

60

```typescript { .api }

61

/**

62

* Reads user input from stdin with configurable options

63

* @param options - Configuration options for input reading

64

* @returns Promise resolving to user input or default value

65

*/

66

function read<T extends string | number = string>(

67

options: Options<T>

68

): Promise<T | string>;

69

```

70

71

**Usage Examples:**

72

73

```typescript

74

// Basic prompt

75

const result = await read({ prompt: "Enter value: " });

76

77

// With default value

78

const name = await read({

79

prompt: "Your name: ",

80

default: "Anonymous"

81

});

82

83

// Silent mode (for passwords)

84

const secret = await read({

85

prompt: "Secret: ",

86

silent: true,

87

replace: "*" // Optional: replace with asterisks

88

});

89

90

// With timeout

91

const quick = await read({

92

prompt: "Quick: ",

93

timeout: 3000

94

});

95

96

// Custom streams

97

const custom = await read({

98

prompt: "Input: ",

99

input: customInputStream,

100

output: customOutputStream

101

});

102

103

// With autocomplete

104

const withCompletion = await read({

105

prompt: "Command: ",

106

completer: (line) => {

107

const commands = ['help', 'exit', 'list'];

108

const hits = commands.filter(cmd => cmd.startsWith(line));

109

return [hits, line];

110

}

111

});

112

113

// With history

114

const withHistory = await read({

115

prompt: "Command: ",

116

history: previousCommands

117

});

118

```

119

120

### Options Interface

121

122

Configuration options for the read function.

123

124

```typescript { .api }

125

interface Options<T extends string | number = string> {

126

/** Default value if user enters nothing */

127

default?: T;

128

129

/** Input stream (default: process.stdin) */

130

input?: ReadLineOptions['input'] & {

131

isTTY?: boolean;

132

};

133

134

/** Output stream (default: process.stdout) */

135

output?: ReadLineOptions['output'] & {

136

isTTY?: boolean;

137

};

138

139

/** Text to display before reading input */

140

prompt?: string;

141

142

/** Don't echo output as user types (for passwords) */

143

silent?: boolean;

144

145

/** Milliseconds to wait before giving up */

146

timeout?: number;

147

148

/** Allow user to edit the default value */

149

edit?: boolean;

150

151

/** Treat output as TTY regardless of actual state */

152

terminal?: boolean;

153

154

/** Character to replace silenced characters with */

155

replace?: string;

156

157

/** Autocomplete callback function */

158

completer?: Completer | AsyncCompleter;

159

160

/** History array for command history */

161

history?: string[];

162

}

163

```

164

165

## Types

166

167

The following types are imported from Node.js built-in modules:

168

169

```typescript { .api }

170

// From 'readline' module

171

type Completer = (line: string) => CompleterResult | Promise<CompleterResult>;

172

type AsyncCompleter = (

173

line: string,

174

callback: (err?: null | Error, result?: CompleterResult) => void

175

) => void;

176

type CompleterResult = [string[], string];

177

178

interface ReadLineOptions {

179

input?: NodeJS.ReadableStream;

180

output?: NodeJS.WritableStream;

181

completer?: Completer | AsyncCompleter;

182

terminal?: boolean;

183

history?: string[];

184

historySize?: number;

185

removeHistoryDuplicates?: boolean;

186

prompt?: string;

187

crlfDelay?: number;

188

escapeCodeTimeout?: number;

189

tabSize?: number;

190

}

191

```

192

193

## Error Handling

194

195

The read function can throw the following errors:

196

197

- **TypeError**: When default value is not a string or number

198

- **Error('timed out')**: When timeout is reached before user input

199

- **Error('canceled')**: When user cancels input with SIGINT (Ctrl+C)

200

201

```typescript

202

try {

203

const result = await read({

204

prompt: "Input: ",

205

default: "valid default", // Must be string or number

206

timeout: 5000

207

});

208

} catch (error) {

209

if (error.message === 'timed out') {

210

console.log('User took too long to respond');

211

} else if (error.message === 'canceled') {

212

console.log('User canceled input');

213

} else {

214

console.log('Invalid configuration:', error.message);

215

}

216

}

217

```

218

219

## Advanced Features

220

221

### Silent Mode with Replacement Characters

222

223

For password input with visual feedback:

224

225

```typescript

226

const password = await read({

227

prompt: "Password: ",

228

silent: true,

229

replace: "•" // Shows bullets instead of characters

230

});

231

```

232

233

### Custom Input/Output Streams

234

235

For testing or alternative interfaces:

236

237

```typescript

238

import { Readable, Writable } from 'stream';

239

240

const customInput = new Readable();

241

const customOutput = new Writable();

242

243

const result = await read({

244

prompt: "Test: ",

245

input: customInput,

246

output: customOutput

247

});

248

```

249

250

### Edit Mode for Defaults

251

252

Allow users to modify default values:

253

254

```typescript

255

const edited = await read({

256

prompt: "Name: ",

257

default: "John Doe",

258

edit: true // User can modify the default

259

});

260

```

261

262

## Platform Compatibility

263

264

- **Node.js Version**: ^18.17.0 || >=20.5.0

265

- **Platforms**: Cross-platform (Windows, macOS, Linux)

266

- **Dependencies**: mute-stream for stream handling

267

- **Module Types**: Supports both CommonJS and ESM