Usando Node.JS, ¿cómo leo un objeto JSON en la memoria (del servidor)?
Fondo
Estoy experimentando con Node.js y le gustaría leer un objeto JSON, ya sea desde un archivo de texto o a .archivo js (¿cuál es mejor??) en la memoria para que pueda acceder a ese objeto rápidamente desde el código. Me doy cuenta de que hay cosas como Mongo, Alfred, etc por ahí, pero eso no es lo que necesito en este momento.
Pregunta
¿Cómo leo un objeto JSON de un archivo de texto o js y en la memoria del servidor usando JavaScript/Node?
7 answers
Sync:
var fs = require('fs');
var obj = JSON.parse(fs.readFileSync('file', 'utf8'));
Async:
var fs = require('fs');
var obj;
fs.readFile('file', 'utf8', function (err, data) {
if (err) throw err;
obj = JSON.parse(data);
});
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
2014-06-26 20:22:12
La forma más fácil que he encontrado para hacer esto es simplemente usar require
y la ruta a su archivo JSON.
Por ejemplo, supongamos que tiene el siguiente archivo JSON.
Prueba.json
{
"firstName": "Joe",
"lastName": "Smith"
}
Puede cargar esto fácilmente en su nodo.aplicación js utilizando require
var config = require('./test.json');
console.log(config.firstName + ' ' + config.lastName);
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
2014-10-19 02:14:04
Asíncrono está ahí por una razón! Lanza piedras a @mihai
De lo contrario, aquí está el código que usó con la versión asíncrona:
// Declare variables
var fs = require('fs'),
obj
// Read the file and send to the callback
fs.readFile('path/to/file', handleFile)
// Write the callback function
function handleFile(err, data) {
if (err) throw err
obj = JSON.parse(data)
// You can now play with your datas
}
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
2012-04-04 12:42:01
Al menos en el nodo v8.9.1, solo puede hacer
var json_data = require('/path/to/local/file.json');
Y accede a todos los elementos del objeto JSON.
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
2017-11-11 03:10:04
En el nodo 8 puede usar el incorporado util.promisify()
para leer asíncronamente un archivo como este
const {promisify} = require('util')
const fs = require('fs')
const readFileAsync = promisify(fs.readFile)
readFileAsync(`${__dirname}/my.json`, {encoding: 'utf8'})
.then(contents => {
const obj = JSON.parse(contents)
console.log(obj)
})
.catch(error => {
throw error
})
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
2017-08-31 12:36:03
Https://nodejs.org/dist/latest-v6.x/docs/api/fs.html#fs_fs_readfile_file_options_callback
var fs = require('fs');
fs.readFile('/etc/passwd', (err, data) => {
if (err) throw err;
console.log(data);
});
// options
fs.readFile('/etc/passwd', 'utf8', callback);
Https://nodejs.org/dist/latest-v6.x/docs/api/fs.html#fs_fs_readfilesync_file_options
Puede encontrar todo el uso de Node.js en los documentos del Sistema de archivos!
espero que esta ayuda para usted!
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
2016-11-02 20:19:39
Si está buscando una solución completa para Async
cargar un archivo JSON desde Relative Path
con Manejo de errores
// Global variables
// Request path module for relative path
const path = require('path')
// Request File System Module
var fs = require('fs');
// GET request for the /list_user page.
router.get('/listUsers', function (req, res) {
console.log("Got a GET request for list of users");
// Create a relative path URL
let reqPath = path.join(__dirname, '../mock/users.json');
//Read JSON from relative path of this file
fs.readFile(reqPath , 'utf8', function (err, data) {
//Handle Error
if(!err) {
//Handle Success
console.log("Success"+data);
// Parse Data to JSON OR
var jsonObj = JSON.parse(data)
//Send back as Response
res.end( data );
}else {
//Handle Error
res.end("Error: "+err )
}
});
})
Estructura De Directorios:
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
2017-10-05 05:04:43