2012-10-03 8 views

Respuesta

25
var fs = require("fs"), 
    json; 

function readJsonFileSync(filepath, encoding){ 

    if (typeof (encoding) == 'undefined'){ 
     encoding = 'utf8'; 
    } 
    var file = fs.readFileSync(filepath, encoding); 
    return JSON.parse(file); 
} 

function getConfig(file){ 

    var filepath = __dirname + '/' + file; 
    return readJsonFileSync(filepath); 
} 

//assume that config.json is in application root 

json = getConfig('config.json'); 
+10

este es el mismo que 'require ('./ config.json')' – Blowsie

+0

esto estaba relacionado con Node.js versiones inferior a V0. 5.x http://stackoverflow.com/questions/7163061/is-there-a-require-for-json-in-node-js – Brankodd

+3

'fs.readFile()' no es lo mismo que 'require()' . Si intenta leer el archivo dos veces con 'fs.readFile()', obtendrá dos punteros diferentes en la memoria. Pero si 'require()' con la misma cadena, señalará el mismo objeto en la memoria, debido al comportamiento de caché de 'required()'. Esto puede conducir a resultados inesperados: cuando la modificación del objeto al que hace referencia el primer puntero cambia inesperadamente el objeto modificado por el segundo puntero. – steampowered

11

Este me funcionó. Usando el modulo fs:

var fs = require('fs'); 

function readJSONFile(filename, callback) { 
    fs.readFile(filename, function (err, data) { 
    if(err) { 
     callback(err); 
     return; 
    } 
    try { 
     callback(null, JSON.parse(data)); 
    } catch(exception) { 
     callback(exception); 
    } 
    }); 
} 

Uso:

readJSONFile('../../data.json', function (err, json) { 
    if(err) { throw err; } 
    console.log(json); 
}); 

Fuente: https://codereview.stackexchange.com/a/26262

+0

Estoy usando exactamente esto y obteniendo 'if (err) {throw err; } SyntaxError: token inesperado} ' – Piet

14

hacer algo como esto en su controlador.

Para obtener la JSON contenido de archivo:

ES5 var foo = require('path/to/your/file.json');

ES6 import foo from '/path/to/your/file.json';

Para enviar la JSON a la vista:

function getJson(req, res, next){ 
    res.send(foo); 
} 

Esto debería enviar el JSON contenido a la vista a través de una solicitud.

NOTA

Según BTMPL

While this will work, do take note that require calls are cached and will return the same object on each subsequent call. Any change you make to the .json file when the server is running will not be reflected in subsequent responses from the server.

+0

Tenga en cuenta que para los archivos locales, necesita el punto/barra anterior adjunto al requerimiento'./' –

Cuestiones relacionadas