or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.md

index.mddocs/

0

# randomstring

1

2

randomstring is a Node.js module for generating random strings with customizable character sets, lengths, and formatting options. It provides both synchronous and asynchronous APIs with cryptographically secure random byte generation and graceful fallback to Math.random() for compatibility.

3

4

## Package Information

5

6

- **Package Name**: randomstring

7

- **Package Type**: npm

8

- **Language**: JavaScript

9

- **Installation**: `npm install randomstring`

10

11

## Core Imports

12

13

```javascript

14

const randomstring = require("randomstring");

15

```

16

17

For ES modules (Node.js with type: "module"):

18

19

```javascript

20

import randomstring from "randomstring";

21

```

22

23

## Basic Usage

24

25

```javascript

26

const randomstring = require("randomstring");

27

28

// Generate default 32-character alphanumeric string

29

const str1 = randomstring.generate();

30

// >> "XwPp9xazJ0ku5CZnlmgAx2Dld8SHkAeT"

31

32

// Generate string with specific length

33

const str2 = randomstring.generate(12);

34

// >> "kJh3Md9xB2nP"

35

36

// Generate string with options

37

const str3 = randomstring.generate({

38

length: 8,

39

charset: 'alphabetic',

40

capitalization: 'lowercase'

41

});

42

// >> "abcdefgh"

43

44

// Generate async with callback

45

randomstring.generate({ length: 16, charset: 'hex' }, (err, result) => {

46

if (err) throw err;

47

console.log(result); // >> "a1b2c3d4e5f67890"

48

});

49

```

50

51

## Architecture

52

53

randomstring is built around several key components:

54

55

- **Random Generation Engine**: Uses Node.js `randombytes` library for cryptographically secure randomness with automatic fallback to `Math.random()` for compatibility

56

- **Charset System**: Flexible character set management supporting predefined sets (alphanumeric, hex, etc.) and custom character strings or arrays

57

- **Dual API**: Both synchronous and asynchronous generation modes with consistent option handling

58

- **CLI Interface**: Command-line tool with flexible argument parsing supporting both positional and key-value parameters

59

60

## Capabilities

61

62

### Random String Generation

63

64

Generates random strings with extensive customization options including character sets, length, capitalization, and readability filtering.

65

66

```javascript { .api }

67

/**

68

* Generate a random string with specified options

69

* @param {number|object} options - Length (number) or options object

70

* @param {function} [callback] - Optional callback for async generation

71

* @returns {string|undefined} Generated string (sync) or undefined (async)

72

*/

73

function generate(options, callback);

74

75

// Options object properties:

76

interface GenerateOptions {

77

/** Length of the generated string (default: 32) */

78

length?: number;

79

80

/** Character set to use for generation (default: 'alphanumeric') */

81

charset?: string | string[];

82

83

/** Exclude poorly readable characters (0OIl) (default: false) */

84

readable?: boolean;

85

86

/** Force case transformation (default: null) */

87

capitalization?: 'uppercase' | 'lowercase';

88

}

89

```

90

91

**Supported Character Sets:**

92

93

- `'alphanumeric'` - [0-9 a-z A-Z] (62 characters)

94

- `'alphabetic'` - [a-z A-Z] (52 characters)

95

- `'numeric'` - [0-9] (10 characters)

96

- `'hex'` - [0-9 a-f] (16 characters)

97

- `'binary'` - [01] (2 characters)

98

- `'octal'` - [0-7] (8 characters)

99

- Custom string - Any string of characters to use

100

- Array of charsets - Combines multiple character sets

101

102

**Usage Examples:**

103

104

```javascript

105

// Simple length specification

106

randomstring.generate(10);

107

108

// Numeric-only string

109

randomstring.generate({

110

length: 16,

111

charset: 'numeric'

112

});

113

114

// Readable alphanumeric (excludes 0OIl)

115

randomstring.generate({

116

length: 20,

117

charset: 'alphanumeric',

118

readable: true

119

});

120

121

// Custom character set

122

randomstring.generate({

123

length: 12,

124

charset: 'abc123'

125

});

126

127

// Array of character sets

128

randomstring.generate({

129

length: 15,

130

charset: ['numeric', '!@#$']

131

});

132

133

// Uppercase only

134

randomstring.generate({

135

length: 8,

136

charset: 'alphabetic',

137

capitalization: 'uppercase'

138

});

139

140

// Async generation

141

randomstring.generate({

142

length: 24,

143

charset: 'hex'

144

}, (err, result) => {

145

if (err) {

146

console.error('Generation failed:', err);

147

return;

148

}

149

console.log('Generated:', result);

150

});

151

```

152

153

## Command Line Interface

154

155

The package includes a command-line interface for generating random strings:

156

157

```bash

158

# Install globally

159

npm install -g randomstring

160

161

# Basic usage

162

randomstring

163

# >> "sKCx49VgtHZ59bJOTLcU0Gr06ogUnDJi"

164

165

# Specify length

166

randomstring 12

167

# >> "CpMg433xB2nP"

168

169

# Use options (key=value format)

170

randomstring length=16 charset=hex readable

171

# >> "a1b2c3d4e5f67890"

172

173

# Mixed usage - positional length + options

174

randomstring 20 charset=alphabetic capitalization=uppercase

175

# >> "ABCDEFGHIJKLMNOPQRST"

176

177

# Available options:

178

# length=N - Set string length (or use as first positional argument)

179

# charset=TYPE - Set character set (alphanumeric, alphabetic, numeric, hex, binary, octal, or custom)

180

# capitalization=CASE - Set case transformation (uppercase/lowercase)

181

# readable - Enable readable mode (excludes 0OIl characters)

182

```

183

184

## Error Handling

185

186

- **Synchronous mode**: No explicit error handling - uses fallback to Math.random() if crypto fails

187

- **Asynchronous mode**: Callback receives error as first parameter if randombytes fails

188

- **Cryptographic fallback**: Automatically falls back to Math.random() when secure random bytes are unavailable

189

190

```javascript

191

// Async error handling

192

randomstring.generate({ length: 100 }, (err, result) => {

193

if (err) {

194

console.error('Random generation error:', err.message);

195

return;

196

}

197

// Use result

198

console.log(result);

199

});

200

```

201

202

## Types

203

204

```javascript { .api }

205

// Main export

206

const randomstring = {

207

generate: function(options, callback)

208

};

209

210

// Options interface (TypeScript-style for documentation)

211

interface GenerateOptions {

212

length?: number;

213

charset?: string | string[];

214

readable?: boolean;

215

capitalization?: 'uppercase' | 'lowercase';

216

}

217

218

// Callback signature

219

type GenerateCallback = (error: Error | null, result?: string) => void;

220

```