我的问题的答案可能是显而易见的,但我找不到它。
我实际上想在nodeJS应用程序上读取一个json文件。
var accRead = fs.readFile(__dirname + '/accounts.JSON', { endoding: 'utf8' }, function(err, data) {
if (err) throw err
if (data) return JSON.parse(data)
})
我写这个,我不明白为什么它返回undefined,我检查了Json文件并且有一些数据。
请尝试以下方法:
const accounts = () => fs.readFileSync(__dirname + '/accounts.json', { endoding: 'utf8'})
const accRead = JSON.parse(accounts())
/*Logging for visualization*/
console.log(accRead)
请尝试以下方法:
fs.readFile(__dirname + '/accounts.JSON', 'utf8', function read(err, dataJSON) {
if (err) {
// handle err
}
else {
// use/process dataJSON
}
})
正如评论中已经提到的,您可以使用函数的同步版本:fs.readFileSync以及..
您也可以在异步函数中打包它,如:
function readJSONfile() {
fs.readFile(__dirname + '/accounts.JSON', 'utf8', function read(err, dataJSON) {
if (err) {
return false
}
else {
return dataJSON
}
})
}
async function () {
let promise1 = new Promise((resolve, reject) => {
resolve(readJSONfile())
});
let result = await promise1; // wait till the promise resolves (*)
if (result == false) {
// handle err
}
else {
// process/use data
}
}
您可以创建一个promise并使用async / await来实现它。
假设你有一个像这样的文件结构:
在accounts.json中你有这个:
[
{
"id": 1,
"username": "test1",
"password": "test1"
},
{
"id": 2,
"username": "test2",
"password": "test2"
},
{
"id": 3,
"username": "test3",
"password": "test3"
}
]
你的index.js文件应该是:
// importing required modules
const fs = require('fs');
const path = require('path');
// building the file path location
const filePath = path.resolve(__dirname, 'accounts.json');
// creating a new function to use async / await syntax
const readFile = async () => {
const fileContent = await new Promise((resolve, reject) => {
return fs.readFile(filePath, { encoding: 'utf8' }, (err, data) => {
if (err) {
return reject(err);
}
return resolve(data);
});
});
// printing the file content
console.log(fileContent);
}
// calling the async function to get started with reading file etc.
readFile();
从节点v0.5.x开始,您可以像需要JSON
文件一样需要JS
。
var someObject = require('./awesome_json.json')
在ES6中:
import someObject from ('./awesome_json.json')
如果你需要字符串只需使用JSON.stringify(someObject)