最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

在子进程中读取JSON文件

运维笔记admin12浏览0评论

在子进程中读取JSON文件

在子进程中读取JSON文件

我有两个相关的节点应用程序。其中一个使用子进程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": ".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": ".simplescan.miniscanner&hl=en&gl=us",
    "appId": "com.simplescan.miniscanner",
    "price": "0",
    "minInstalls": 100000,
    "score": 4.6,
    "version": "1.0.9"
  }
]

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

回答如下:

我运行代码下面试图模拟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);
});

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论