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

解析文件并将其存储到具有Node js中多个值的Map函数中

运维笔记admin12浏览0评论

解析文件并将其存储到具有Node js中多个值的Map函数中

解析文件并将其存储到具有Node js中多个值的Map函数中

我正在解析以下文件格式:

// URL //

帐户/ 42

//状态//

200

// // HEADERS

内容类型=应用/ JSON

//身体//

{“name”:“xyz”}

// URL //

帐户/ 43

我想在map函数中存储单个键的多个值。

电流输出

{ url: [ undefined, 'account/42', undefined, 'account/43' ],

 status: [ undefined, '200' ],

 headers: [ undefined, 'content-type=application/json' ],

 body: [ undefined, '{ "name": "xyz" }' ] }

预期产出

{ url: [ 'account/42', 'account/43' ],

 status: [ '200' ],

 headers: [  'content-type=application/json' ],

 body: [  '{ "name": "xyz" }' ] }

下面是代码

var fs = require('fs');

function parseFile(){

var content;

fs.readFile("src/main/resources/FileData1.txt", function(err, data) {

    if(err) throw err;

    content = data.toString().split(/(?:\r\n|\r|\n)/g).map(function(line){

        return line.trim();

    }).filter(Boolean) 
    console.log(processFile(content));

});

}

function processFile(nodes) {

var map={};

var key;

nodes.forEach(function(node) {

    var value;

    if(node.startsWith("//")){

        key = node.substring(2, node.length-2).toLowerCase();     

    }

    else{

        value = node;

    }

   // map[key] = value;

    if(key in map){

        map[key].push(value);

    }else{

        map[key]= [value]; 
    }
});

return map;    

}

好吧,我可以看到问题是声明“值”,因为我想存储多个值,我不知道何时以及如何声明该值。即使我将值声明为全局值,它也会存储前一个值。问题:如何在地图中存储多个值?

回答如下:

您遇到的问题是在您已确定线路是关键字后继续。在此之后身体继续执行:

if(node.startsWith("//")){
    key = node.substring(2, node.length-2).toLowerCase();           
}

并最终点击您分配值的部分。但是价值没有定义,因为这条线是key。一个简单的解决方法是在设置密钥后返回:

if(node.startsWith("//")){
    key = node.substring(2, node.length-2).toLowerCase();     
    return; // continue to the next line
}

工作范例:

// data after parsing text
let data = [ '//URL//','account/42','//Status//','200','//HEADERS//','content-type=application/json','//BODY//','{ "name": "xyz" }','//URL//','account/43' ]

function processFile(nodes) {

  var map = {};
  var key;

  nodes.forEach(function(node) {
    var value;
    if (node.startsWith("//")) {
      key = node.substring(2, node.length - 2).toLowerCase();
      return
    } else {
      value = node;
    }

    // map[key] = value;

    if (key in map) {
      map[key].push(value);
    } else {
      map[key] = [value];
    }
  });

  return map;
}
let m = processFile(data)
console.log(m)
发布评论

评论列表(0)

  1. 暂无评论