or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

dumping.mderrors.mdindex.mdloading.mdschemas.md
tile.json

dumping.mddocs/

0

# YAML Dumping

1

2

The dumping functionality in js-yaml provides comprehensive YAML serialization capabilities, converting JavaScript objects to YAML strings with extensive formatting and style control options.

3

4

## Core Dumping Function

5

6

### dump

7

8

Serializes a JavaScript object as a YAML document string.

9

10

```javascript { .api }

11

function dump(input, options);

12

```

13

14

**Parameters:**

15

- `input` (any): JavaScript value to serialize (object, array, string, number, boolean, null)

16

- `options` (DumpOptions, optional): Serialization configuration options

17

18

**Returns:** YAML string representation of the input

19

20

**Throws:** `YAMLException` if input contains non-serializable values (unless `skipInvalid: true`)

21

22

**Usage Examples:**

23

24

```javascript

25

const yaml = require('js-yaml');

26

27

// Basic serialization

28

const obj = {

29

name: 'John Doe',

30

age: 30,

31

skills: ['JavaScript', 'YAML', 'Node.js'],

32

active: true

33

};

34

35

const yamlString = yaml.dump(obj);

36

console.log(yamlString);

37

```

38

39

## Dump Options

40

41

### DumpOptions Interface

42

43

```javascript { .api }

44

interface DumpOptions {

45

indent?: number;

46

noArrayIndent?: boolean;

47

skipInvalid?: boolean;

48

flowLevel?: number;

49

styles?: object;

50

schema?: Schema;

51

sortKeys?: boolean | ((a: string, b: string) => number);

52

lineWidth?: number;

53

noRefs?: boolean;

54

noCompatMode?: boolean;

55

condenseFlow?: boolean;

56

quotingType?: '"' | "'";

57

forceQuotes?: boolean;

58

replacer?: (key: string, value: any) => any;

59

}

60

```

61

62

### Indentation Control

63

64

**indent** - Controls indentation width in spaces (default: 2):

65

66

```javascript

67

yaml.dump(obj, { indent: 4 });

68

// Output with 4-space indentation

69

```

70

71

**noArrayIndent** - When `true`, doesn't add indentation level to array elements:

72

73

```javascript

74

const data = { items: ['a', 'b', 'c'] };

75

76

// Default behavior

77

yaml.dump(data);

78

// items:

79

// - a

80

// - b

81

82

// With noArrayIndent: true

83

yaml.dump(data, { noArrayIndent: true });

84

// items:

85

// - a

86

// - b

87

```

88

89

### Error Handling

90

91

**skipInvalid** - Skip invalid types instead of throwing errors:

92

93

```javascript

94

const objWithFunction = {

95

name: 'test',

96

callback: function() { return 'hello'; },

97

data: [1, 2, 3]

98

};

99

100

// Throws error by default

101

try {

102

yaml.dump(objWithFunction);

103

} catch (e) {

104

console.log('Cannot serialize function');

105

}

106

107

// Skip invalid types

108

const result = yaml.dump(objWithFunction, { skipInvalid: true });

109

// Only serializes 'name' and 'data', skips 'callback'

110

```

111

112

### Flow vs Block Style

113

114

**flowLevel** - Controls when to switch from block to flow style (-1 = always block):

115

116

```javascript

117

const nested = {

118

level1: {

119

level2: {

120

level3: { key: 'value' }

121

}

122

}

123

};

124

125

// Always block style (default)

126

yaml.dump(nested, { flowLevel: -1 });

127

128

// Switch to flow at level 2

129

yaml.dump(nested, { flowLevel: 1 });

130

// level1:

131

// level2: { level3: { key: value } }

132

```

133

134

### Key Sorting

135

136

**sortKeys** - Sort object keys in output:

137

138

```javascript

139

const unordered = { z: 1, a: 2, m: 3 };

140

141

// Sort alphabetically

142

yaml.dump(unordered, { sortKeys: true });

143

// a: 2

144

// m: 3

145

// z: 1

146

147

// Custom sort function

148

yaml.dump(unordered, {

149

sortKeys: (a, b) => b.localeCompare(a) // Reverse alphabetical

150

});

151

```

152

153

### Line Width Control

154

155

**lineWidth** - Maximum line width for text wrapping (default: 80, -1 = unlimited):

156

157

```javascript

158

const longText = { description: 'A very long text that exceeds normal line width...' };

159

160

yaml.dump(longText, { lineWidth: 40 });

161

// description: >-

162

// A very long text that exceeds normal

163

// line width...

164

165

yaml.dump(longText, { lineWidth: -1 });

166

// No line wrapping

167

```

168

169

### Reference Handling

170

171

**noRefs** - Disable object reference conversion for duplicate objects:

172

173

```javascript

174

const shared = { shared: 'data' };

175

const obj = { ref1: shared, ref2: shared };

176

177

// Default: uses YAML references

178

yaml.dump(obj);

179

// ref1: &ref_0

180

// shared: data

181

// ref2: *ref_0

182

183

// With noRefs: true

184

yaml.dump(obj, { noRefs: true });

185

// ref1:

186

// shared: data

187

// ref2:

188

// shared: data

189

```

190

191

### String Quoting

192

193

**quotingType** - Preferred quote style for strings:

194

195

```javascript

196

const strings = { single: "text with 'quotes'", double: 'text with "quotes"' };

197

198

yaml.dump(strings, { quotingType: '"' });

199

// Use double quotes when needed

200

201

yaml.dump(strings, { quotingType: "'" });

202

// Use single quotes when needed (default)

203

```

204

205

**forceQuotes** - Force quote all non-key strings:

206

207

```javascript

208

const data = { key: 'simple text', number: '123' };

209

210

yaml.dump(data, { forceQuotes: true });

211

// key: 'simple text'

212

// number: '123'

213

```

214

215

### Compatibility

216

217

**noCompatMode** - Disable YAML 1.1 compatibility features:

218

219

```javascript

220

const booleans = { yes: true, no: false, on: true };

221

222

// Default: quotes ambiguous values for YAML 1.1 compatibility

223

yaml.dump(booleans);

224

// 'yes': true

225

// 'no': false

226

227

// With noCompatMode: true

228

yaml.dump(booleans, { noCompatMode: true });

229

// yes: true

230

// no: false

231

```

232

233

**condenseFlow** - Condense flow sequences and mappings:

234

235

```javascript

236

const flow = { list: ['a', 'b', 'c'], map: { x: 1, y: 2 } };

237

238

yaml.dump(flow, { flowLevel: 0, condenseFlow: true });

239

// {list: [a,b,c], map: {x: 1,y: 2}}

240

```

241

242

### Schema Control

243

244

**schema** - Specify schema for serialization:

245

246

```javascript

247

yaml.dump(data, { schema: yaml.JSON_SCHEMA });

248

// Only uses JSON-compatible types

249

```

250

251

### Value Transformation

252

253

**replacer** - Transform values during serialization:

254

255

```javascript

256

const data = {

257

created: new Date('2023-01-01'),

258

secret: 'password123',

259

value: 42

260

};

261

262

yaml.dump(data, {

263

replacer: (key, value) => {

264

if (key === 'secret') return '[REDACTED]';

265

if (value instanceof Date) return value.toISOString();

266

return value;

267

}

268

});

269

```

270

271

## Type-Specific Styling

272

273

Control how specific YAML types are formatted using the `styles` option:

274

275

```javascript { .api }

276

interface StylesMap {

277

[tagName: string]: string;

278

}

279

```

280

281

### Built-in Type Styles

282

283

**!!null styles:**

284

- `"canonical"``"~"`

285

- `"lowercase"``"null"` (default)

286

- `"uppercase"``"NULL"`

287

- `"camelcase"``"Null"`

288

289

**!!int styles:**

290

- `"binary"``"0b1101"`

291

- `"octal"``"0o15"`

292

- `"decimal"``"13"` (default)

293

- `"hexadecimal"``"0xD"`

294

295

**!!bool styles:**

296

- `"lowercase"``"true"`, `"false"` (default)

297

- `"uppercase"``"TRUE"`, `"FALSE"`

298

- `"camelcase"``"True"`, `"False"`

299

300

**!!float styles:**

301

- `"lowercase"``".nan"`, `".inf"` (default)

302

- `"uppercase"``".NAN"`, `".INF"`

303

- `"camelcase"``".NaN"`, `".Inf"`

304

305

### Style Usage Example

306

307

```javascript

308

const data = {

309

active: null,

310

count: 42,

311

flag: true,

312

ratio: Number.POSITIVE_INFINITY

313

};

314

315

yaml.dump(data, {

316

styles: {

317

'!!null': 'canonical', // Use ~ for null

318

'!!int': 'hexadecimal', // Use hex for integers

319

'!!bool': 'uppercase', // Use TRUE/FALSE

320

'!!float': 'uppercase' // Use .INF/.NAN

321

}

322

});

323

324

// Output:

325

// active: ~

326

// count: 0x2A

327

// flag: TRUE

328

// ratio: .INF

329

```

330

331

## Common Patterns

332

333

### Configuration File Generation

334

335

```javascript

336

function generateConfig(config) {

337

return yaml.dump(config, {

338

indent: 2,

339

lineWidth: 120,

340

sortKeys: true,

341

noCompatMode: true,

342

styles: {

343

'!!null': 'lowercase',

344

'!!bool': 'lowercase'

345

}

346

});

347

}

348

```

349

350

### Data Export with Formatting

351

352

```javascript

353

function exportData(data, format = 'readable') {

354

const options = {

355

readable: {

356

indent: 2,

357

lineWidth: 80,

358

flowLevel: -1

359

},

360

compact: {

361

indent: 0,

362

lineWidth: -1,

363

flowLevel: 0,

364

condenseFlow: true

365

},

366

safe: {

367

skipInvalid: true,

368

noRefs: true,

369

schema: yaml.CORE_SCHEMA

370

}

371

};

372

373

return yaml.dump(data, options[format] || options.readable);

374

}

375

```