Javascript 使用 Node.JS,如何将 JSON 文件读入(服务器)内存?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10011011/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using Node.JS, how do I read a JSON file into (server) memory?
提问by Matt Cashatt
Background
背景
I am doing some experimentation with Node.js and would like to read a JSON object, either from a text file or a .js file (which is better??) into memory so that I can access that object quickly from code. I realize that there are things like Mongo, Alfred, etc out there, but that is not what I need right now.
我正在对 Node.js 进行一些实验,并希望将 JSON 对象从文本文件或 .js 文件(哪个更好??)读取到内存中,以便我可以从代码中快速访问该对象。我意识到有像 Mongo、Alfred 等这样的东西,但这不是我现在需要的。
Question
题
How do I read a JSON object out of a text or js file and into server memory using JavaScript/Node?
如何使用 JavaScript/Node 从文本或 js 文件中读取 JSON 对象并读取到服务器内存中?
回答by mihai
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);
});
回答by Travis Tidwell
The easiest way I have found to do this is to just use require
and the path to your JSON file.
我发现这样做的最简单方法是使用require
JSON 文件的路径。
For example, suppose you have the following JSON file.
例如,假设您有以下 JSON 文件。
test.json
测试文件
{
"firstName": "Joe",
"lastName": "Smith"
}
You can then easily load this in your node.js application using require
然后,您可以使用 require
var config = require('./test.json');
console.log(config.firstName + ' ' + config.lastName);
回答by Florian Margaine
Asynchronous is there for a reason! Throws stone at @mihai
异步是有原因的!向@mihai 扔石头
Otherwise, here is the code he used with the asynchronous version:
否则,这是他用于异步版本的代码:
// 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
}
回答by Alex Eftimiades
At least in Node v8.9.1, you can just do
至少在 Node v8.9.1 中,你可以这样做
var json_data = require('/path/to/local/file.json');
var json_data = require('/path/to/local/file.json');
and access all the elements of the JSON object.
并访问 JSON 对象的所有元素。
回答by J P
In Node 8 you can use the built-in util.promisify()
to asynchronously read a file like this
在 Node 8 中,您可以使用内置util.promisify()
来异步读取这样的文件
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
})
回答by ifelse.codes
using node-fs-extra(async await)
使用node-fs-extra (异步等待)
const readJsonFile = async () => {
try {
const myJsonObject = await fs.readJson('./my_json_file.json');
console.log(myJsonObject);
} catch (err) {
console.error(err)
}
}
readJsonFile() // prints your json object
回答by Arturo Menchaca
Using fs-extrapackage is quite simple:
使用fs-extra包非常简单:
Sync:
同步:
const fs = require('fs-extra')
const packageObj = fs.readJsonSync('./package.json')
console.log(packageObj.version)
Async:
异步:
const fs = require('fs-extra')
const packageObj = await fs.readJson('./package.json')
console.log(packageObj.version)
回答by Satyabrata Saha
function parseIt(){
return new Promise(function(res){
try{
var fs = require('fs');
const dirPath = 'K:\merge-xml-junit\xml-results\master.json';
fs.readFile(dirPath,'utf8',function(err,data){
if(err) throw err;
res(data);
})}
catch(err){
res(err);
}
});
}
async function test(){
jsonData = await parseIt();
var parsedJSON = JSON.parse(jsonData);
var testSuite = parsedJSON['testsuites']['testsuite'];
console.log(testSuite);
}
test();
回答by xgqfrms
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_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
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!
hope this help for you!
您可以在文件系统文档中找到 Node.js 的所有用法!
希望这对你有帮助!