如何使用node.js

时间:2017-09-11 20:00:09

标签: javascript node.js filesystems writefile

我想要这种格式

 1   {"index": {"_id": 0}}
 2   { "age_groups" : ["-KmQN3SH7_ ........100000 words in sinle line
 3   {"index": {"_id": 1}}
 4   { "age_groups" : ["-KmQN3SH7_ ........100000 words in sinle line
 5   {"index": {"_id": 2}}
 6   { "age_groups" : ["-KmQN3SH7_ ........100000 words in sinle line
 7   {"index": {"_id": 3}}
 8   { "age_groups" : ["-KmQN3SH7_ ........100000 words in sinle line

但是我在写完文件后得到了这种格式。

{"index": {"_id": 0}}
{ "age_groups" : ["-KmQN3SH7_P73cwZrSmD","-KmQN6Aze7LROyH_cCpP","-"-KmQNKlhHrO0AnnAGybq"],  "needs": ["-Km5n7VJ_X5j2Yj9aG6c","-Km5ncKlPDe8C4nFq6kG"], "categories": ["-KmCtR9mDf_CvwtS3B74","-KmCter6Woj-xM1jPNs4"], "tags": , "title": "Bepanthol - Intensive Κρέμα Προσώπου & Ματιών - 50ml", "code": "113829", "brand": "Bepanthol", "price_bought": "0", "price_sell": "16.05", "weight": "50ml", "description": "<h3><span style="font-size:12px"><strong>Bepanthol</strong></span></h3>

有人可以告诉我如何实现这一目标吗?

这是我的代码:

const fs = require('fs');
const jsonfile = require('jsonfile');

var logger = fs.createWriteStream('./Exports/log1.txt', {
  flags: 'a' // 'a' means appending (old data will be preserved)
})

function convertProducts_fs() {



  const selectedFile = document.getElementById('inp_products_fs').files[0];
  const filePath = selectedFile.path;
  const fileToRead = filePath;

  jsonfile.readFile(fileToRead, function(err, data) {

    let counter = 0;
    for (let key in data) {

      if (data.hasOwnProperty(key)) {

        let element = data[key];
        let SCHEMA = {};

        SCHEMA.age_groups = [];
        SCHEMA.needs = [];
        SCHEMA.categories = [];
        SCHEMA.tags = [];

        SCHEMA.title = element.title;
        SCHEMA.code = element.custom_id;
        SCHEMA.brand = element.brand;
        SCHEMA.price_bought = element.bought_price;
        SCHEMA.price_sell = element.sell_price;
        SCHEMA.weight = element.weight;
        SCHEMA.description = element.description;
        SCHEMA.uses = element.uses;

        SCHEMA.created = element.timestamp;
        SCHEMA.updated = element.timestamp;
        SCHEMA.image_url = '';
        SCHEMA.added_by = 'admin@gmail.com';
        SCHEMA.status = 'inactive';


        for (let _key1 in element.age_groups) {
          SCHEMA.age_groups.push(_key1);
        }

        for (let _key2 in element.needs) {
          SCHEMA.needs.push(_key2);
        }

        for (let _key3 in element.final_category) {
          SCHEMA.categories.push(_key3);
        }


        SCHEMA.created = element.timestamp;
        SCHEMA.updated = element.timestamp;


        let age_groups = JSON.stringify(SCHEMA.age_groups);
        let needs = JSON.stringify(SCHEMA.needs);
        let categories = JSON.stringify(SCHEMA.categories);

        logger.write(`{"index": {"_id": ${counter}}}`) // append string to your file
        logger.write('\r\n')
        logger.write(`{ "age_groups" : ${age_groups},  "needs": ${needs}, "categories": ${categories}, "tags": ${SCHEMA.tags}, "title": "${SCHEMA.title}", "code": "${SCHEMA.code}", "brand": "${SCHEMA.brand}", "price_bought": "${SCHEMA.price_bought}", "price_sell": "${SCHEMA.price_sell}", "weight": "${SCHEMA.weight}", "description": "${SCHEMA.description}", "uses": "${SCHEMA.uses}" }`) // append string to your file
        logger.write('\r\n')
      }

      counter++;


    }

    logger.end();

  });

}

1 个答案:

答案 0 :(得分:1)

如果我已正确理解问题从这里开始:

"tags": ${SCHEMA.tags}

你没有按照JSON.stringify的方式传递这个值,就像你对早期值所做的那样,所以它只是被包含在未编码状态,包括其中的所有换行符。

在该行上还有其他几个类似的未编码值。

比较输出categories的方式:

let categories = JSON.stringify(SCHEMA.categories);

"categories": ${categories}

输出tags的方式:

"tags": ${SCHEMA.tags}

所有这一切,避免以这种零敲碎打的方式构建JSON会更容易,只需使用:

logger.write(JSON.stringify(SCHEMA));

如果您只想输出某些属性,可以使用:

logger.write(JSON.stringify(SCHEMA, ['age_groups', 'needs', /* etc. */]));