lijiarui / lijiarui/nodejs-_study
关于JsonRead 的同步异步问题
- Dominant language
- No language data
- Stars
- 0
- Forks
- 0
- PR merge metrics
- No merged PRs in 30d
Description
```shell
const fs = require('fs');
const path = require("path");
// settings file path
const groupjsonPath = path.join(__dirname, 'config', 'group.json');
let testJson = getGroupJson()
console.log(testJson)
export async function getGroupJson() {
console.log("%%%%%%%%%%%")
return readJsonFile(groupjsonPath);
}
function readJsonFile(filePath) {
let info = {};
fs.readFileSync(filePath, 'utf8', (err, data) => {
if (err) throw err;
console.log(data)
info = JSON.parse(data);
return info;
});
}
```
### 上述代码,打印出的结果为:
```
%%%%%%%%%%%
Promise { undefined }
```
所以这里的`fs.readFileSync()`方法并没有成功有效果,甚至在`readFileSync` 里面的`console.log(data)`中的data也没有打印出来。
### 我做了微调整:
当我把`fs.readFileSync(filePath, 'utf8', (err, data)`改为`fs.readFile(filePath, 'utf8', (err, data)`之后,整体打印结果为:
```
%%%%%%%%%%%
Promise { undefined }
{。。。。}//可以打印出console.log(data)内容,具体内容此处省略
```
### 我继续做调整,加入了await:
```
export async function getGroupJson() {
console.log("%%%%%%%%%%%")
return await readJsonFile(groupjsonPath);
}
```
打印日志后,发现只有`Promise{ undefined }` 变成了 `Promise { }`
唔。。。怎样才能成功的调用getJson获取到Json结果呢?
Contributor guide
No contributing guide indexed for this repository
Research direction
Start with the getGroupJson and readJsonFile snippets in the issue, then compare the documented behavior of fs.readFileSync and fs.readFile. Trace how the return value is consumed and confirm what output should represent a successfully parsed group.json; the issue is resolved when the caller can obtain that JSON value and the observed logging matches the chosen synchronous or asynchronous flow.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- javascript, node.js
- Domain
- backend
- Issue type
- Bug
- Difficulty
- 2/5
- Estimated time
- 1-3 hours
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 30/100