or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

browser-rendering.mdconfiguration.mdcore-generation.mdindex.mdserver-operations.mdstring-rendering.md

server-operations.mddocs/

0

# Server-side File Operations

1

2

Server-only functions for saving QR codes to files, generating buffers, and streaming output. These functions are available only in Node.js environments and provide comprehensive file system integration.

3

4

## Capabilities

5

6

### File Output

7

8

Saves QR codes directly to image files with automatic format detection.

9

10

```javascript { .api }

11

/**

12

* Saves QR Code to image file

13

* @param {string} path - File path to save to

14

* @param {string|Array} text - Text to encode or segments

15

* @param {Object} options - File and rendering options

16

* @param {Function} callback - Completion callback

17

* @returns {Promise} Promise when using async/await

18

*/

19

function toFile(path, text, options, callback);

20

```

21

22

**Usage Examples:**

23

24

```javascript

25

const QRCode = require('qrcode');

26

27

// Save as PNG (default)

28

QRCode.toFile('qrcode.png', 'Hello World', function (err) {

29

if (err) throw err;

30

console.log('QR code saved as PNG');

31

});

32

33

// Save as SVG

34

QRCode.toFile('qrcode.svg', 'Hello World', function (err) {

35

if (err) throw err;

36

console.log('QR code saved as SVG');

37

});

38

39

// Save as UTF-8 text

40

QRCode.toFile('qrcode.txt', 'Hello World', function (err) {

41

if (err) throw err;

42

console.log('QR code saved as text');

43

});

44

45

// Format detection from extension

46

QRCode.toFile('output.png', 'Hello World'); // PNG

47

QRCode.toFile('output.svg', 'Hello World'); // SVG

48

QRCode.toFile('output.txt', 'Hello World'); // UTF-8

49

50

// Explicit format specification

51

QRCode.toFile('output.png', 'Hello World', {

52

type: 'png',

53

width: 300,

54

color: {

55

dark: '#0000FF',

56

light: '#FFFFFF'

57

}

58

});

59

60

// Using Promises

61

try {

62

await QRCode.toFile('qr.png', 'Hello World', { width: 400 });

63

console.log('File saved successfully');

64

} catch (err) {

65

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

66

}

67

```

68

69

### Buffer Generation

70

71

Generates QR codes as Node.js buffers for in-memory processing.

72

73

```javascript { .api }

74

/**

75

* Generates QR code as Node.js Buffer

76

* @param {string|Array} text - Text to encode or segments

77

* @param {Object} options - Buffer generation options

78

* @param {Function} callback - Callback with (error, buffer)

79

* @returns {Promise<Buffer>} Buffer when using promises

80

*/

81

function toBuffer(text, options, callback);

82

```

83

84

**Usage Examples:**

85

86

```javascript

87

// Generate PNG buffer

88

QRCode.toBuffer('Hello World', function (err, buffer) {

89

if (err) throw err;

90

91

console.log('Buffer size:', buffer.length);

92

console.log('Buffer type:', typeof buffer); // 'object' (Buffer)

93

94

// Write buffer to file manually

95

require('fs').writeFileSync('manual.png', buffer);

96

});

97

98

// Generate SVG buffer

99

QRCode.toBuffer('Hello World', { type: 'svg' }, function (err, buffer) {

100

if (err) throw err;

101

102

// Convert to string for SVG

103

const svgString = buffer.toString('utf8');

104

console.log(svgString); // <svg xmlns="http://www.w3.org/2000/svg"...

105

});

106

107

// Generate UTF-8 text buffer

108

QRCode.toBuffer('Hello World', { type: 'utf8' }, function (err, buffer) {

109

if (err) throw err;

110

111

const textQR = buffer.toString('utf8');

112

console.log(textQR); // ASCII art QR code

113

});

114

115

// Custom PNG options

116

QRCode.toBuffer('Hello World', {

117

type: 'png',

118

width: 500,

119

rendererOpts: {

120

deflateLevel: 9, // Maximum compression

121

deflateStrategy: 3 // Default strategy

122

}

123

}, function (err, buffer) {

124

console.log('Compressed PNG buffer:', buffer.length, 'bytes');

125

});

126

127

// Using Promises

128

try {

129

const buffer = await QRCode.toBuffer('Hello World', { type: 'png' });

130

131

// Process buffer (send via HTTP, store in database, etc.)

132

console.log('Generated buffer:', buffer.length, 'bytes');

133

} catch (err) {

134

console.error('Buffer generation failed:', err);

135

}

136

```

137

138

### Stream Output

139

140

Writes QR codes directly to Node.js streams (PNG format only).

141

142

```javascript { .api }

143

/**

144

* Writes QR Code to a writable stream (PNG only)

145

* @param {stream.Writable} stream - Destination stream

146

* @param {string|Array} text - Text to encode or segments

147

* @param {Object} options - Stream writing options

148

*/

149

function toFileStream(stream, text, options);

150

```

151

152

**Usage Examples:**

153

154

```javascript

155

const fs = require('fs');

156

const QRCode = require('qrcode');

157

158

// Write to file stream

159

const writeStream = fs.createWriteStream('stream-output.png');

160

QRCode.toFileStream(writeStream, 'Hello Stream World', {

161

width: 300,

162

color: { dark: '#FF0000' }

163

});

164

165

writeStream.on('finish', () => {

166

console.log('QR code written to stream');

167

});

168

169

writeStream.on('error', (err) => {

170

console.error('Stream error:', err);

171

});

172

173

// Write to HTTP response stream

174

const http = require('http');

175

176

const server = http.createServer((req, res) => {

177

res.writeHead(200, {

178

'Content-Type': 'image/png',

179

'Content-Disposition': 'attachment; filename="qrcode.png"'

180

});

181

182

QRCode.toFileStream(res, req.url.slice(1) || 'Default QR Code', {

183

width: 200

184

});

185

});

186

187

// Write to any writable stream

188

const { PassThrough } = require('stream');

189

const passThrough = new PassThrough();

190

191

QRCode.toFileStream(passThrough, 'Stream Data', { width: 250 });

192

193

passThrough.on('data', (chunk) => {

194

console.log('Received chunk:', chunk.length, 'bytes');

195

});

196

197

passThrough.on('end', () => {

198

console.log('Stream ended');

199

});

200

```

201

202

## Server-Specific Options

203

204

### PNG File Options

205

206

PNG-specific options for file and buffer generation:

207

208

```javascript { .api }

209

interface PNGOptions {

210

/** Output type */

211

type: 'png';

212

213

/** PNG-specific renderer options */

214

rendererOpts?: {

215

/** Deflate compression level (0-9) */

216

deflateLevel?: number; // Default: 9

217

/** Deflate compression strategy (0-3) */

218

deflateStrategy?: number; // Default: 3

219

};

220

}

221

```

222

223

**Examples:**

224

225

```javascript

226

// Maximum compression (slower, smaller files)

227

QRCode.toFile('compressed.png', 'text', {

228

type: 'png',

229

rendererOpts: {

230

deflateLevel: 9,

231

deflateStrategy: 3

232

}

233

});

234

235

// Fast compression (faster, larger files)

236

QRCode.toFile('fast.png', 'text', {

237

type: 'png',

238

rendererOpts: {

239

deflateLevel: 1,

240

deflateStrategy: 0

241

}

242

});

243

244

// No compression (fastest, largest files)

245

QRCode.toFile('uncompressed.png', 'text', {

246

type: 'png',

247

rendererOpts: {

248

deflateLevel: 0

249

}

250

});

251

```

252

253

### SVG File Options

254

255

SVG files support all standard rendering options:

256

257

```javascript

258

QRCode.toFile('styled.svg', 'SVG QR Code', {

259

type: 'svg',

260

width: 300,

261

margin: 2,

262

color: {

263

dark: '#000080',

264

light: '#FFFFFF'

265

}

266

});

267

```

268

269

### UTF-8 Text Options

270

271

Text files support terminal rendering options:

272

273

```javascript

274

QRCode.toFile('qr.txt', 'Text QR', {

275

type: 'utf8',

276

small: false, // Full-size terminal output

277

inverse: false // Normal colors

278

});

279

```

280

281

## File Format Detection

282

283

The `toFile()` function automatically detects format from file extension:

284

285

```javascript

286

// Recognized extensions and their formats

287

QRCode.toFile('qr.png', 'text'); // PNG format

288

QRCode.toFile('qr.svg', 'text'); // SVG format

289

QRCode.toFile('qr.txt', 'text'); // UTF-8 text format

290

291

// Override auto-detection

292

QRCode.toFile('qr.png', 'text', { type: 'svg' }); // Saves SVG despite .png extension

293

294

// Unknown extensions default to PNG

295

QRCode.toFile('qr.xyz', 'text'); // PNG format

296

```

297

298

## Error Handling

299

300

Server operations can encounter file system and format-specific errors:

301

302

```javascript

303

// File system errors

304

QRCode.toFile('/readonly/path.png', 'text', function (err) {

305

if (err) {

306

console.log(err.code); // 'EACCES', 'ENOENT', etc.

307

console.log(err.message); // File system error message

308

}

309

});

310

311

// Invalid path errors

312

QRCode.toFile('', 'text', function (err) {

313

if (err) {

314

console.log(err.message); // "Invalid argument"

315

}

316

});

317

318

// Stream errors

319

const badStream = fs.createWriteStream('/invalid/path.png');

320

QRCode.toFileStream(badStream, 'text');

321

322

badStream.on('error', (err) => {

323

console.log('Stream error:', err.message);

324

});

325

326

// Buffer generation errors

327

QRCode.toBuffer('text', { type: 'invalid' }, function (err, buffer) {

328

if (err) {

329

console.log(err.message); // Format-specific error

330

}

331

});

332

```

333

334

## Integration Examples

335

336

### Express.js Server

337

338

```javascript

339

const express = require('express');

340

const QRCode = require('qrcode');

341

342

const app = express();

343

344

// Generate QR code as response

345

app.get('/qr/:text', async (req, res) => {

346

try {

347

const buffer = await QRCode.toBuffer(req.params.text, {

348

width: 300,

349

type: 'png'

350

});

351

352

res.setHeader('Content-Type', 'image/png');

353

res.setHeader('Content-Length', buffer.length);

354

res.send(buffer);

355

} catch (err) {

356

res.status(500).json({ error: err.message });

357

}

358

});

359

360

// Stream QR code directly to response

361

app.get('/qr-stream/:text', (req, res) => {

362

res.setHeader('Content-Type', 'image/png');

363

QRCode.toFileStream(res, req.params.text, { width: 250 });

364

});

365

```

366

367

### File Processing Pipeline

368

369

```javascript

370

const fs = require('fs');

371

const path = require('path');

372

const QRCode = require('qrcode');

373

374

// Batch QR code generation

375

async function generateQRCodes(texts, outputDir) {

376

for (let i = 0; i < texts.length; i++) {

377

const text = texts[i];

378

const filename = path.join(outputDir, `qr_${i}.png`);

379

380

try {

381

await QRCode.toFile(filename, text, {

382

width: 300,

383

color: { dark: '#000080' }

384

});

385

console.log(`Generated: ${filename}`);

386

} catch (err) {

387

console.error(`Failed to generate ${filename}: ${err.message}`);

388

}

389

}

390

}

391

392

// Usage

393

generateQRCodes(['Hello', 'World', 'QR Codes'], './output/');

394

```

395

396

### Database Integration

397

398

```javascript

399

const QRCode = require('qrcode');

400

401

// Store QR codes as binary data

402

async function storeQRCode(text, database) {

403

try {

404

const buffer = await QRCode.toBuffer(text, {

405

type: 'png',

406

width: 200

407

});

408

409

// Store buffer in database

410

await database.qrcodes.insert({

411

text: text,

412

image: buffer,

413

created: new Date()

414

});

415

416

console.log('QR code stored in database');

417

} catch (err) {

418

console.error('Database storage failed:', err);

419

}

420

}

421

```