hay un requisito para json en el nodo.js


Me gustaría incluir un par de archivos JSON en mi código JavaScript que están en el mismo directorio que mi archivo fuente JavaScript.

Si quisiera incluir otro archivo JavaScript, simplemente podría usar require. Ahora estoy usando readFileSync y __dirname para obtener el JSON, que creo que es una forma fea de hacerlo.

¿Hay algo similar para require que me permita cargar un archivo JSON?

Author: Kirill, 2011-08-23

4 answers

A partir del nodo v0. 5.x sí, puede requerir su JSON del mismo modo que requeriría un archivo js.

var someObject = require('./somefile.json')

En ES6:

import someObject from ('./somefile.json')

 330
Author: goatslacker,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-29 11:57:17

No. Utilice readFile o readFileSync (este último solo en el momento del inicio).

O utilice una biblioteca existente como

Alternativamente escriba su configuración en un archivo js en lugar de un archivo json como

module.exports = {
  // json
}
 15
Author: Raynos,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-08-23 15:04:17

Los archivos JSON no requieren una instrucción explícita exports. No es necesario exportar para usarlo como archivos Javascript.

Por lo tanto, puede usar solo require para un documento JSON válido.

data.json

{
  "name": "Freddie Mercury"
}

main.js

var obj = require('data.json');

console.log(obj.name); 
//Freddie Mercury
 11
Author: serkan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-07 08:18:01

Incluso puede usar require de su JSON sin especificar la extensión .json . Le permitirá cambiar la extensión del archivo a .js sin ningún cambio en sus importaciones.

Asumiendo que tenemos ./ myJsonFile.json en el mismo directorio.

const data = require('./myJsonFile')

Si en el futuro cambias ./ myJsonFile.json a ./ myJsonFile.js no se debe cambiar nada en la importación.

 0
Author: Igor Litvinovich,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-06 09:07:00