or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

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

loading.mddocs/

0

# YAML Loading

1

2

The loading functionality in js-yaml provides comprehensive YAML parsing capabilities, supporting both single and multi-document YAML sources with extensive configuration options.

3

4

## Core Loading Functions

5

6

### load

7

8

Parses a single YAML document from a string.

9

10

```javascript { .api }

11

function load(input, options);

12

```

13

14

**Parameters:**

15

- `input` (string): YAML string to parse

16

- `options` (LoadOptions, optional): Parsing configuration options

17

18

**Returns:** The parsed JavaScript value (object, array, string, number, boolean, null, or undefined)

19

20

**Throws:** `YAMLException` on parsing errors

21

22

**Usage Examples:**

23

24

```javascript

25

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

26

27

// Basic parsing

28

const simple = yaml.load('hello: world');

29

// Result: { hello: 'world' }

30

31

// Parse different data types

32

const data = yaml.load(`

33

name: John Doe

34

age: 30

35

active: true

36

skills:

37

- JavaScript

38

- YAML

39

- Node.js

40

`);

41

42

// With options

43

const doc = yaml.load(yamlString, {

44

filename: 'config.yml',

45

schema: yaml.JSON_SCHEMA,

46

onWarning: (warning) => console.warn(warning.toString())

47

});

48

```

49

50

### loadAll

51

52

Parses multiple YAML documents from a single string, separated by `---` document separators.

53

54

```javascript { .api }

55

function loadAll(input, iterator, options);

56

function loadAll(input, options);

57

```

58

59

**Parameters:**

60

- `input` (string): YAML string containing multiple documents

61

- `iterator` (function, optional): Function called for each parsed document

62

- `options` (LoadOptions, optional): Parsing configuration options

63

64

**Returns:** Array of parsed documents (if no iterator provided)

65

66

**Usage Examples:**

67

68

```javascript

69

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

70

71

const multiDoc = `

72

---

73

name: Document 1

74

type: config

75

---

76

name: Document 2

77

type: data

78

---

79

items: [1, 2, 3]

80

`;

81

82

// Using iterator

83

yaml.loadAll(multiDoc, (doc) => {

84

console.log('Parsed document:', doc);

85

});

86

87

// Getting array of documents

88

const docs = yaml.loadAll(multiDoc);

89

console.log(`Found ${docs.length} documents`);

90

```

91

92

## Loading Options

93

94

### LoadOptions Interface

95

96

```javascript { .api }

97

interface LoadOptions {

98

filename?: string;

99

onWarning?: (warning: YAMLException) => void;

100

schema?: Schema;

101

json?: boolean;

102

}

103

```

104

105

### filename

106

107

Specifies a filename to be used in error and warning messages for better debugging.

108

109

```javascript

110

const doc = yaml.load(yamlContent, {

111

filename: 'config.yaml'

112

});

113

```

114

115

### onWarning

116

117

Callback function to handle parsing warnings without stopping the parsing process.

118

119

```javascript

120

const doc = yaml.load(yamlContent, {

121

onWarning: (warning) => {

122

console.warn(`YAML Warning: ${warning.message}`);

123

console.warn(`Location: line ${warning.mark.line + 1}, column ${warning.mark.column + 1}`);

124

}

125

});

126

```

127

128

### schema

129

130

Specifies which YAML schema to use for parsing. Controls which types are recognized.

131

132

```javascript

133

// Use JSON schema (no custom types)

134

const doc = yaml.load(yamlContent, {

135

schema: yaml.JSON_SCHEMA

136

});

137

138

// Use default schema (all supported types)

139

const doc = yaml.load(yamlContent, {

140

schema: yaml.DEFAULT_SCHEMA

141

});

142

```

143

144

Available schemas:

145

- `yaml.FAILSAFE_SCHEMA` - Only strings, sequences, and mappings

146

- `yaml.JSON_SCHEMA` - JSON-compatible types (null, boolean, integer, float)

147

- `yaml.CORE_SCHEMA` - Same as JSON_SCHEMA

148

- `yaml.DEFAULT_SCHEMA` - All supported types including timestamps, binary, etc.

149

150

### json

151

152

When `true`, enables JSON compatibility mode where duplicate keys in mappings will override previous values instead of throwing an error.

153

154

```javascript

155

const yamlWithDuplicates = `

156

key: first value

157

key: second value

158

`;

159

160

// Normally throws error

161

try {

162

yaml.load(yamlWithDuplicates);

163

} catch (e) {

164

console.log('Error: duplicate key');

165

}

166

167

// With json: true, uses last value

168

const doc = yaml.load(yamlWithDuplicates, { json: true });

169

console.log(doc.key); // "second value"

170

```

171

172

## Error Handling

173

174

Loading functions throw `YAMLException` for parsing errors:

175

176

```javascript

177

try {

178

const doc = yaml.load('invalid: yaml: syntax');

179

} catch (e) {

180

if (e instanceof yaml.YAMLException) {

181

console.log('YAML Error:', e.reason);

182

console.log('Position:', e.mark);

183

console.log('Snippet:', e.mark.snippet);

184

}

185

}

186

```

187

188

## Common Patterns

189

190

### Safe File Loading

191

192

```javascript

193

const fs = require('fs');

194

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

195

196

function loadYamlFile(filepath) {

197

try {

198

const content = fs.readFileSync(filepath, 'utf8');

199

return yaml.load(content, { filename: filepath });

200

} catch (e) {

201

if (e instanceof yaml.YAMLException) {

202

console.error(`YAML parsing error in ${filepath}:`, e.message);

203

} else {

204

console.error(`File read error:`, e.message);

205

}

206

throw e;

207

}

208

}

209

```

210

211

### Configuration Loading with Validation

212

213

```javascript

214

function loadConfig(yamlString) {

215

const config = yaml.load(yamlString, {

216

schema: yaml.CORE_SCHEMA, // Restrict to basic types

217

onWarning: (warning) => console.warn(`Config warning: ${warning.message}`)

218

});

219

220

// Validate required fields

221

if (!config.database || !config.server) {

222

throw new Error('Missing required configuration sections');

223

}

224

225

return config;

226

}

227

```