简体   繁体   English

fs.WriteFile() 返回 NULL 并且不写入 JSON 文件

[英]fs.WriteFile() returning NULL and not writing to JSON file

I have a Javascript file that writes data to my "sequence.json" file.我有一个 Javascript 文件,它将数据写入我的“sequence.json”文件。 However, I keep getting reiterations of NULL returned in my console.但是,我不断在控制台中返回NULL的重复。 Then when I view my "sequence.json" file, it updates, but updates to "\"i\": 99" or whatever the last iterated number was based off inputNum .然后,当我查看我的“sequence.json”文件时,它会更新,但会更新为"\"i\": 99"或任何基于inputNum的最后迭代数字。 The JSON file also doesn't look like a JSON, it should look like an array of objects like this: JSON 文件看起来也不像 JSON,它应该看起来像这样的对象数组:

[{"i":1,"addedSum":2},{ "i":2,"addedSum":4 }]

Here is my code in order.这是我的代码。 it may have a lot of errors, this was my first attempt at something like this, so apologies if it's a bit messy.它可能有很多错误,这是我第一次尝试这样的事情,所以如果它有点混乱,请道歉。

Required fs and used readFileSync():必需的 fs 和使用的 readFileSync():

var fs = require("fs");
const data = fs.readFileSync("sequence.json");
var numberCount = JSON.parse(data);
let numberObj = JSON.stringify(numberCount);

let inputNum = 100;

InitCount() initializes the count and is suppose to push i and addedSum to my "sequence.json" file. InitCount()初始化计数并假设将iaddedSum推送到我的“sequence.json”文件中。 Instead, it returns iterations of NULL with my sequence.JSON file only containing: "\"i\": 99" .相反,它返回NULL的迭代,我的 sequence.JSON 文件仅包含: "\"i\": 99"

const InitCount = (inputNum) => {
  for (let i = 0; i < inputNum; i++) {
    let addedSum = i + i;
    console.log(i);
    let data = JSON.stringify(`"i": ${i}`, `addedSum:${addedSum}`);

    fs.writeFile("sequence.json", data, finished);
    function finished(err) {
      console.log(err);
    }
  }
};

addCount() is supposed to look at the last number in "sequence.JSON" and continue the count if inputNum is > than the last number in the array. addCount()应该查看“sequence.JSON”中的最后一个数字,如果inputNum大于数组中的最后一个数字,则继续计数。 Example: If the array is empty, and you input 100, the sequence.JSON file should reflect 100 objects.示例:如果数组为空,并且您输入 100,则 sequence.JSON 文件应反映 100 个对象。 If you then were to input 200, then its function is supposed to identify that the last number in the "sequence.json" array, i , was 100, and continue the count up to 200, of course starting from 101, then add and write the new numbers onto "sequence.JSON".如果你然后输入 200,那么它的 function 应该识别“sequence.json”数组中的最后一个数字i是 100,然后继续计数到 200,当然从 101 开始,然后添加和将新数字写入“sequence.JSON”。

function addCount(arr, inputNum) {
  let i = arr.length;
  for (i ? arr[i - 1].len + 1 : 0; i <= inputNum; i++) {
    let addedSum = i + i;
    let data = JSON.stringify(`"i": ${i}`, `addedSum:${addedSum}`);

    fs.writeFile("sequence.json", data, finished);
    function finished(err) {
      console.log(err);
    }
    addCount(numberObj, inputNum);
  }
}
return InitCount(inputNum);

Update: Code returning error Cannot read property 'readFile' of undefined更新:代码返回错误Cannot read property 'readFile' of undefined

const fs = require("fs");

let inputNum = 200;

async function readSequenceJSON() {
  let data = await fs.promises.readFile("numberLine.json");
  return JSON.parse(data);
}

function writeSequenceJSON(data) {
  let str = JSON.stringify(data);
  return fs.promises.writefile("numberLine.json", str);
}

async function nextSequence(inputNum) {
  let data = await readSequenceJSON();

  for (let i = 0; i <= inputNum; i++) {
    const addedSum = i + i; 
    // only push numbers whose frequencies are "in bounds" of num
    if (frequency <= inputNum) {
      data.push({ i, addedSum });
    }
  }

  function addValues(data, inputNum) {
    for (
      let i = data.length ? data[data.length - 1].i + 1 : 0;
      i <= inputNum;
      i++
    ) {
      const addedSum = i + i;
      data.push({ i, addedSum });
    }
  }

Your for loop is attempting to start a whole bunch of fs.writeFile() operations such that they are ALL trying to write to the file at the same time.for循环正在尝试启动一大堆fs.writeFile()操作,以便它们都试图同时写入文件。 This will clearly cause problems and conflicts.这显然会导致问题和冲突。 It doesn't really make sense to be calling fs.writeFile() over and over on the same file in a loop because each new write will just overwrite what was previously written, even if you sequence them one at a time.在循环中对同一个文件反复调用fs.writeFile()并没有真正的意义,因为每次新的写入只会覆盖以前写入的内容,即使您一次对它们进行排序。

In addition, you're passing two strings to JSON.stringify() where the second string would be interpreted as a replacer which is supposed to be either a function or an array, but you're passing a string.此外,您将两个字符串传递给JSON.stringify() ,其中第二个字符串将被解释为替换器,它应该是 function 或数组,但您传递的是字符串。 So, that doesn't make sense either.所以,这也没有意义。

Then, you appear to be calling addCount() recursively forever.然后,您似乎一直在递归调用addCount() That also doesn't make sense.这也没有道理。

I honestly cannot tell exactly what you're trying to accomplish with your sequence.json file so I'll offer a small tutorial on writing a new item to that sequence.老实说,我无法准确地告诉您要使用您的 sequence.json 文件完成什么,所以我将提供一个关于向该序列写入新项目的小教程。

Let's suppose you have a sequence.json that initially contains:假设您有一个sequence.json最初包含:

[{"i":1,"addedSum":2}]

And, you want to find the last i and addedSum values in that array and create the next item in the sequence.并且,您想在该数组中找到最后一个iaddedSum值,并在序列中创建下一项。 To do that, you would following these steps:为此,您将执行以下步骤:

  1. Read in the existing JSON读入现有的 JSON
  2. Parse it into a Javascript object将其解析为 Javascript object
  3. Using it as Javascript, get the last item in the array and look at the i and addedSum values there.将其用作 Javascript,获取数组中的最后一项并查看那里的iaddedSum值。
  4. Create the new object you want to add to the end of the array and add it to the array创建新的 object 你想添加到数组的末尾并添加到数组中
  5. Convert the modified array to JSON and write to to your file.将修改后的数组转换为 JSON 并写入您的文件。

Code here:代码在这里:

async function readSequenceJSON() {
     let data = await fs.promises.readFile('sequence.json');
     return JSON.parse(data);
}

function writeSequenceJSON(data) {
     let str = JSON.stringify(data);
     return fs.promises.writeFile('sequence.json', str);
}

async function nextSequence(input) {
      let data = await readSequenceJSON();

      // do some processing of data here to possibly add a new item
      // insert your code here, data is a Javascript object (no JSON)
      // data[data.length - 1] references the last object in the array
      // if that is key to your processing

      return writeSequenceJSON(data);
}

// how to call it
nextSequence(someInput).then(() => {
    console.log("all done");
}).catch(err => {
    console.log(err);
});

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

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