How to use the safeLoad function from js-yaml

Find comprehensive JavaScript js-yaml.safeLoad code examples handpicked from public code repositorys.

js-yaml.safeLoad is a function in the js-yaml library that loads a YAML string and returns its corresponding JavaScript object in a safe and secure manner.

83
84
85
86
87
88
89
90
91
92
describe("verify other YAML files", function () {
  const files = ["backers.yml", "blocked-scopes.yml", "builtin.yml", "sponsors.yml", "topics.yml"];
  for (const file of files) {
    let absPath = path.resolve(dataDir, file);
    it("verify " + file, function() {
      const result = yaml.safeLoad(fs.readFileSync(absPath, "utf8"));
      result.should.not.be.undefined();
    });
  }
});
fork icon571
star icon0
watch icon9

+ 3 other calls in file

48
49
50
51
52
53
54
55
56
57
  return result;
}

let result;
try {
  result = YAML.safeLoad(str);
  debug('parse: YAML:', str, result);
} catch (parseErr) {
  throw parseErr;
}
fork icon438
star icon0
watch icon62

How does js-yaml.safeLoad work?

js-yaml.safeLoad is a function in the js-yaml library that loads a YAML string and returns its corresponding JavaScript object in a safe and secure manner. When you call js-yaml.safeLoad, the function first checks if the YAML string contains any malicious code or constructs that could cause security issues. If the YAML string is safe, js-yaml.safeLoad parses the string and returns its corresponding JavaScript object. If the YAML string is not safe, js-yaml.safeLoad throws an error to prevent the execution of any potentially harmful code. Here's an implementation of js-yaml.safeLoad to illustrate how it works: javascript Copy code {{{{{{{ const jsyaml = require('js-yaml'); jsyaml.safeLoad = (str, options) => { try { const parsed = jsyaml.load(str, options); if (parsed === null || typeof parsed === 'object') { return parsed; } else { throw new Error('Unsafe YAML type'); } } catch (error) { throw new Error(`Safe load error: ${error.message}`); } }; In this implementation, we extend the js-yaml library by adding a new method called safeLoad using jsyaml.safeLoad = (str, options) => {...}. The safeLoad method takes a YAML string as its first argument and an optional options object as its second argument. We then try to parse the YAML string using jsyaml.load(str, options). If the YAML string is safe, js-yaml.safeLoad checks if the parsed object is either null or an object using if (parsed === null || typeof parsed === 'object'). If the parsed object is null or an object, js-yaml.safeLoad returns it. If the parsed object is not null or an object, js-yaml.safeLoad throws an error to prevent the execution of any potentially harmful code. If an error occurs during parsing, js-yaml.safeLoad throws an error with the message Safe load error: ${error.message} to indicate that an error occurred during a safe load. Overall, js-yaml.safeLoad is a useful function in the js-yaml library that allows you to load YAML strings in a safe and secure manner.

59
60
61
62
63
64
65
66
67
68
69
70
        .on('error', done)
        .pipe(sink())
    )


function loadSampleUiModel (src) {
  return fs.readFile(ospath.join(src, 'ui-model.yml'), 'utf8').then((contents) => yaml.safeLoad(contents))
}


function registerPartials (src) {
  return vfs.src('partials/*.hbs', { base: src, cwd: src }).pipe(
fork icon38
star icon137
watch icon7

135
136
137
138
139
140
141
142
143
144
145
 */
exports.loadFile = file => {
  // if the file doesnt exist then return an empty object
  if (!fs.existsSync(file)) return {};
  // otherwise load the file and return it
  return yaml.safeLoad(fs.readFileSync(file));
};


/*
 * Uses _.mergeWith to concat arrays, this helps replicate how Docker Compose
fork icon35
star icon29
watch icon4

+ 21 other calls in file

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const jsyaml = require("js-yaml");

const yamlString = `
name: John
age: 30
address:
street: 123 Main St
city: Anytown
state: CA
`;

const data = jsyaml.safeLoad(yamlString);

console.log(data);
// Output: { name: 'John', age: 30, address: { street: '123 Main St', city: 'Anytown', state: 'CA' } }

In this example, we first require the js-yaml library using const jsyaml = require('js-yaml'). We then define a YAML string called yamlString that contains some key-value pairs and nested objects. We then call jsyaml.safeLoad(yamlString) to parse the YAML string and return its corresponding JavaScript object. Since the YAML string is safe, js-yaml.safeLoad returns the JavaScript object that represents the YAML string. Finally, we log the data variable to the console, which outputs the JavaScript object: css Copy code

251
252
253
254
255
256
257
258
259
260
function getUnreleasedChangelogs(files) {
    let release = {};
    files.forEach(function (file) {
        if (file !== 'config.json') {
            let fileContents = fs.readFileSync(changelogPath + '/' + file, 'utf8');
            let data = yaml.safeLoad(fileContents);
            if (typeof release[data['type']] === 'undefined') {
                release[data['type']] = [];
            }

fork icon1
star icon2
watch icon2

+ 4 other calls in file

1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472


function lint(content, opts, cb) {


  var options = merge({}, DEFAULT_LINT_OPTION, opts);
  try {
    yaml.safeLoad(content, {
      schema: yaml[options.schema]
    });
    cb();
  } catch (e) {
fork icon0
star icon15
watch icon3

33
34
35
36
37
38
39
40
41
42

const nycrcYamlFilename = join(workingDirectory, '.nycrc.yaml')
let nycrcYaml = {}
if (existsSync(nycrcYamlFilename)) {
  try {
    nycrcYaml = yaml.safeLoad(readFileSync(nycrcYamlFilename, 'utf8'))
  } catch (error) {
    throw new Error(`Failed to load .nycrc.yaml: ${error.message}`)
  }
}
fork icon1
star icon8
watch icon1

+ 9 other calls in file

126
127
128
129
130
131
132
133
134
135
it(`should return a filled template as a string when format is 'string'`, () => {
  const data = { test: { array: ['item3'], key: 'item3', value: '3' } }
  const filled = loadTemplate(
    { data, format: 'string' },
    utilValues.ymlStr,
    yaml.safeLoad
  )
  expect(typeof filled).toEqual('string')
  expect(filled.includes('- item3')).toBe(true)
  expect(filled.includes('item3: 3')).toBe(true)
fork icon1
star icon0
watch icon1

+ 3 other calls in file

17
18
19
20
21
22
23
24
25
26
const yaml = require('js-yaml');
const fs = require('fs');
let config = {};
var rootKey;
try {
    config = yaml.safeLoad(fs.readFileSync('./drops/test.yaml', 'utf8'));
    console.log(config);
    for(var prop in config) {
    	 console.log( prop ); //will give "services"
    	 rootKey = prop;
fork icon0
star icon1
watch icon2

20
21
22
23
24
25
26
27
28
29
const gateway = new Gateway();

const userName = 'isabella';

// Load connection profile; will be used to locate a gateway
let connectionProfile = yaml.safeLoad(fs.readFileSync('../gateway/connection-org2.yaml', 'utf8'));

// Set connection options; identity and wallet
let connectionOptions = {
    identity: userName,
fork icon0
star icon0
watch icon1

32
33
34
35
36
37
38
39
40
  return console.log(err);
}

// Turn string from file to an Array
if (fileName.endsWith('yaml') || fileName.endsWith('yml')) {
  dataArray = YAML.safeLoad(data);
} else {
  dataArray = JSON.parse(data);
}
fork icon0
star icon0
watch icon0

+ 4 other calls in file

24
25
26
27
28
29
30
31
32

    if (Array.isArray(defaults.plugins)) {
        defaults.plugins = preparePluginsArray(config, defaults.plugins);
    }
} else {
    defaults = Object.assign({}, yaml.safeLoad(FS.readFileSync(__dirname + '/../../.svgo.yml', 'utf8')));
    defaults.plugins = preparePluginsArray(config, defaults.plugins || []);
    defaults = extendConfig(defaults, config);
}
fork icon0
star icon0
watch icon1

+ 3 other calls in file

48
49
50
51
52
53
54
55
56
57
      if (stat && stat.isDirectory()) {
        /* Recurse into a subdirectory */
        results[name] = walk(file);
      } else {
        /* Is a file */
        results[name] = yaml.safeLoad(fs.readFileSync(file, 'utf-8'));
      }
    });
  return results;
};
fork icon0
star icon0
watch icon1

+ 4 other calls in file

126
127
128
129
130
131
132
133
134

  if (typeof value !== "string") {
    throw new Error(`value is not a string`);
  }

  value = yaml.safeLoad(value);
} catch (e) {
  throw new Error(`${__filename} yaml parse error: ${e}`);
}
fork icon0
star icon0
watch icon1

+ 15 other calls in file

151
152
153
154
155
156
157
158
159
160

  ind[i].v += yml[k] + "\n";
}

for (let i = 0, l = ind.length; i < l; i += 1) {
  ind[i].v = yaml.safeLoad(ind[i].v);
}

return {
  ind,
fork icon0
star icon0
watch icon1

+ 7 other calls in file

88
89
90
91
92
93
94
95
96
97
98
99
100
101
102


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


let yml = fs.readFileSync(file, "utf8").toString();


yml = yaml.safeLoad(yml);


const ret = get(yml, key);


if (isObject(ret) || isArray(ret)) {
fork icon0
star icon0
watch icon1

+ 7 other calls in file

22
23
24
25
26
27
28
29
30
31
const util = require('./util');
const specSources = require('./spec_sources');
const sp = require('./sortParameters.js');
var httpCache;
try {
  httpCache = YAML.safeLoad(fs.readFileSync(pathLib.join(__dirname,'../metadata/httpCache.yaml'),'utf8'));
}
catch (ex) {
  console.log(ex.message);
  httpCache = { cache: [] };
fork icon0
star icon0
watch icon5

+ 14 other calls in file

20
21
22
23
24
25
26
27
28
29
30
31
exports.readYaml = function (filename) {
  if (!fs.existsSync(filename))
    return;


  var data = fs.readFileSync(filename, 'utf-8');
  return YAML.safeLoad(data, {filename: filename, schema:YAML.JSON_SCHEMA});
}


exports.readJson = function (filename) {
  if (!fs.existsSync(filename))
fork icon0
star icon0
watch icon5

+ 2 other calls in file

15
16
17
18
19
20
21
22
23
24
constructor(port, openApiYaml) {
  this.port = port;
  this.app = express();
  this.openApiPath = openApiYaml;
  try {
    this.schema = jsYaml.safeLoad(fs.readFileSync(openApiYaml));
  } catch (e) {
    logger.error('failed to start Express Server', e.message);
  }
  this.setupMiddleware();
fork icon0
star icon0
watch icon1

53
54
55
56
57
58
59
60
61
62
63
var glob = require('glob');
var fs = require('fs');
var path = require('path');
var async = require('async');
var yaml = require('js-yaml');
var jekyllConfig = yaml.safeLoad(fs.readFileSync('_config.yml'));
var ignore = require('ignore')().add(jekyllConfig.exclude)


var personal = fs
  .readFileSync(path.join(__dirname, 'dictionary.txt'), 'utf8')
fork icon0
star icon0
watch icon1