gpt4 book ai didi

javascript - 在子进程中读取 JSON 文件

转载 作者:太空宇宙 更新时间:2023-11-03 22:25:10 26 4
gpt4 key购买 nike

我有两个相关的 Node 应用程序。其中一个是使用子进程 exec 方法从另一个调用的。在提到的应用程序中,我正在使用此方法读取一些 JSON 文件:

function readAsync(files, configs, callBack) {
var result = [];
files.forEach(function (item, i) {
result = result.concat(JSON.parse(fs.readFileSync(item, { encoding: 'utf8' })));
if (i === files.length - 1 && typeof (callBack) === 'function') {
var _ret = _.chain(result)
.uniqBy(function (x) { return x.url })
.sortBy(function (x) { return x.title })
.value();
filterByConfigs(_ret, configs, function (filteredResult) {
callBack(filteredResult);
});
}
})}

我在读取和解析 JSON 文件时遇到此错误。但是,当我独立运行子应用程序时,没有任何错误和问题。

undefined:1

SyntaxError: Unexpected end of JSON input
at Object.parse (native)
at E:\Open Source Projects\src\cli\readFiles.js:30:37
at Array.forEach (native)
at readAsync (E:\Open Source Projects\src\cli\readFiles.js:29:11)
at E:\Open Source Projects\src\cli\readFiles.js:19:9
at E:\Open Source Projects\src\cli\getJsonFiles.js:18:13
at FSReqWrap.oncomplete (fs.js:123:15)

JSON 文件示例:

[
{
"title": "Document Manager",
"subTitle": "Document manager - indexing, Filter file and rename - delete - share document.",
"url": "https://play.google.com/store/apps/details?id=com.document.manager.filescanner&hl=en&gl=us",
"appId": "com.document.manager.filescanner",
"price": "0",
"minInstalls": 1000000,
"score": 4.2,
"version": "1.4"
},
{
"title": "Mini Scanner - PDF Scanner App",
"subTitle": "Fast easy way to scanner, professional pdf documents, Support SD card + Send Fax",
"url": "https://play.google.com/store/apps/details?id=com.simplescan.miniscanner&hl=en&gl=us",
"appId": "com.simplescan.miniscanner",
"price": "0",
"minInstalls": 100000,
"score": 4.6,
"version": "1.0.9"
}
]

有人遇到过这种情况吗?谢谢。

最佳答案

我运行下面的代码尝试模拟问题,当文件有不完整或损坏的 json 时,我得到了结果。在尝试记录读取/解析错误时,您能否验证在 console.log 中获得的内容?

var fs = require("fs");
function readAsync(files, configs, callBack) {
var result = [];
files.forEach(function (item, i) {

console.log("reading file:", item);
try{
result = result.concat(JSON.parse(fs.readFileSync(item, { encoding: 'utf8' })));
}catch(ex){
console.log("bad file :c :", item, ex);
}
if (i === files.length - 1 && typeof (callBack) === 'function'){
callBack(result);
}
});
}

readAsync([ "test.json" ], null, function(obj){
console.log(obj);
});

关于javascript - 在子进程中读取 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47859117/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com