var fs = require('fs');
var obj = JSON.parse(fs.readFileSync('file', 'utf8'));
异步:
var fs = require('fs');
var obj;
fs.readFile('file', 'utf8', function (err, data) {
if (err) throw err;
obj = JSON.parse(data);
});
-2
我发现这样做的最简单方法是使用 require 和JSON文件的路径 .
例如,假设您有以下JSON文件 .
test.json
{
"firstName": "Joe",
"lastName": "Smith"
}
然后,您可以使用 require 在node.js应用程序中轻松加载它
var config = require('./test.json');
console.log(config.firstName + ' ' + config.lastName);
320
异步是有原因的!在@mihai扔石头
否则,这是他与异步版本一起使用的代码:
// 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
}
19
至少在Node v8.9.1中,你可以做到
var json_data = require('/path/to/local/file.json');
You can find all usage of Node.js at the File System docs! 希望对你有所帮助!
902
If you are looking for a complete solution for Async loading a JSON file from Relative Path with Error Handling
// 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 )
}
});
})
7 回答
同步:
异步:
我发现这样做的最简单方法是使用
require
和JSON文件的路径 .例如,假设您有以下JSON文件 .
test.json
然后,您可以使用
require
在node.js应用程序中轻松加载它异步是有原因的!在@mihai扔石头
否则,这是他与异步版本一起使用的代码:
至少在Node v8.9.1中,你可以做到
var json_data = require('/path/to/local/file.json');
并访问JSON对象的所有元素 .
在Node 8中,您可以使用内置的
util.promisify()
来异步读取这样的文件https://nodejs.org/dist/latest-v6.x/docs/api/fs.html#fs_fs_readfile_file_options_callback
https://nodejs.org/dist/latest-v6.x/docs/api/fs.html#fs_fs_readfilesync_file_options
You can find all usage of Node.js at the File System docs!
希望对你有所帮助!
If you are looking for a complete solution for Async loading a JSON file from Relative Path with Error Handling
Directory Structure: