Mi configuración: VS Code+ WSL2. Los archivos están todos en la misma carpeta (js-ayml.js, el archivo YAML y el index.html). Ejecuto el código javascript actualizando una página que hace referencia a él. Uso la extensión de código GoLive VS como servidor
<!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)); }); }); }()); Publiqué esto Leyendo YAML desde JavaScript en un navegador y estaba cerrado.
He intentado esto:
https://stackify.dev/804643-reading-from-yaml-file-in-javascript (Solución 2)
y el ejemplo que se muestra aquí
https://github.com/shockey/js-yaml-browser esto dice que esta bifurcación está optimizada para navegadores
Todos fallan con el mismo error.
js-yaml.js:9 Uncaught ReferenceError: require is not defined at js-yaml.js:9:16 Esa línea es var fs = require('fs'); Según tengo entendido, fs es un módulo node.js y no funcionará en el navegador
Mi pregunta es ¿Existe un módulo de JavaScript para abrir y leer archivos YAML desde un servidor web, un módulo que funcione en el navegador sin ningún backend?
Nota: soy un principiante y pensé que este sería un ejemplo básico, cargue un archivo y analícelo.
shockey/js-yaml-browser está dañado y no se ha actualizado en varios años. js-yaml en general tiene muchas bifurcaciones. Manx7/js-yaml funciona y está razonablemente actualizado.
.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>