我有两个相关的节点应用程序。其中一个使用子进程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"
}
]
有没有人遇到过这种情况呢?感谢。
答案 0 :(得分:0)
我运行代码以试图模拟te问题,当文件有不完整或损坏的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);
});