简体   繁体   English

如何将字符添加到 node.js 或 javascript 中的行尾

[英]How to add character to the end of the line in node js or javascript

I have a file that has 6,000 of json. Its raw data and I need to add an comma ', ' to the end of each line.我有一个包含 6,000 个 json 的文件。它是原始数据,我需要在每一行的末尾添加一个逗号“,”。 Can someone help.有人可以帮忙吗。 Current code is creating a new line with a comma I need comma at end of each line.当前代码正在创建一个带有逗号的新行,我需要在每行末尾使用逗号。 Node.js or Javascript example is acceptable Node.js 或 Javascript 示例是可以接受的

The data file:数据文件:

{"id": "67", "ac": []}
{"id": "78","ac": []}
{"id": "90", "ac": []}

What I am currently getting:我目前得到的是:

{"id": "67", "ac": []}
,
{"id": "78","ac": []}
,
{"id": "90", "ac": []}

What I need我需要的

{"id": "67", "ac": []},
{"id": "78","ac": []},
{"id": "90", "ac": []},

Current code当前代码

"use strict";

const fs = require("fs");

fs.readFile("users.json", (err, data) => {
  if (err) throw err;
  let student = data.toString();

  var lines = student.split(/(\n|\r\n)/);

  var new_content = lines
    .map(function (line) {
      return line + ",";
    })
    .join("\r\n");
  fs.writeFile("newFile.json", new_content, (err) => {
    if (err) throw err;
    console.log("Data written to file");
  });

Looking at your code, it looks like your trying to mutate a string by adding the comma in the map function. 'line' is immutable so you cant add the comma, but you can reassign the value;查看您的代码,您似乎试图通过在 map function 中添加逗号来改变字符串。'line' 是不可变的,因此您不能添加逗号,但您可以重新分配值; IE line = line += ',' or newValue = line += ',' then return the value after that. IE line = line += ',' 或 newValue = line += ',' 然后返回之后的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM