Reputation: 1285
My setup: VS Code+ WSL2. Files are all in the same folder (js-ayml.js, the YAML file and the index.html). I run the javascript code by refreshing a page that refers to it. I use the GoLive VS code extension as server
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="fr">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Test js-yaml</title>
<script src="//code.jquery.com/jquery-2.1.0.js">
</script><script src='js-yaml.js'>
</script><script src='readYaml.js'>
</head>
<body>
<h1>Test js-yaml</h1>
<p><a href="https://github.com/nodeca/js-yaml">https://github.com/nodeca/js-yaml</a></p>
</body>
</html>
readYaml.js
(function () {
"use strict";
$(document).ready(function () {
$.get('/common/resources/LessonContentsLv01Ln01.yml')
.done(function (data) {
console.log('File load complete');
console.log(jsyaml.load(data));
var jsonString = JSON.stringify(data);
console.log(jsonString);
console.log($.parseJSON(jsonString));
});
});
}());
I have posted this https://stackoverflow.com/questions/70916217/reading-yaml-from-javascript-in-a-browser?noredirect=1#comment125366890_70916217 and it was closed.
I have tried this:
Reading from YAML File in Javascript (Solution 2)
and the example shown here
https://github.com/shockey/js-yaml-browser this says this fork is optimized for browsers
They all fail with the same error
js-yaml.js:9 Uncaught ReferenceError: require is not defined
at js-yaml.js:9:16
That line is var fs = require('fs');
As far as I understand fs is a node.js module and it won't work in the browser
My question is Is there a JavaScript module to open and read YAML files from a web server, a module that works in the browser without any backend?
Note: I am a beginner and I thought this would be a basic example, load a file and parse it.
Upvotes: 0
Views: 4076
Reputation: 16896
shockey/js-yaml-browser
is broken and hasn't been updated in several years. js-yaml
in general has a lot of forks. Manx7/js-yaml
works and is reasonably up to date.
.as-console-wrapper { top: 0; max-height: 100% !important; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-yaml/4.1.0/js-yaml.js"></script>
<script>
// Normally we'd use fetch to get the file. However, stackoverflow
// snippets don't have a way to add another file, so we'll use a
// string instead just to show how the library works.
/*
fetch("sample.yaml")
.then(response => response.text())
.then(text => {
// once the file has been loaded, we can parse it into an object.
const yaml = jsyaml.load(text);
console.log(yaml);
});
*/
const text = `
# Employee records
- martin:
name: Martin D'vloper
job: Developer
skills:
- python
- perl
- pascal
- tabitha:
name: Tabitha Bitumen
job: Developer
skills:
- lisp
- fortran
- erlang
`;
const yaml = jsyaml.load(text);
console.log(yaml);
</script>
Upvotes: 1