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

King Muze

I have a Javascript file that writes data to my "sequence.json" file. However, I keep getting reiterations of NULL returned in my console. 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. The JSON file also doesn't look like a JSON, it should look like an array of objects like this:

[{"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():

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. Instead, it returns iterations of NULL with my sequence.JSON file only containing: "\"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. Example: If the array is empty, and you input 100, the sequence.JSON file should reflect 100 objects. 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".

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

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 });
    }
  }

jfriend00

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. 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.

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. So, that doesn't make sense either.

Then, you appear to be calling addCount() recursively forever. 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.

Let's suppose you have a sequence.json that initially contains:

[{"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. To do that, you would following these steps:

  1. Read in the existing JSON
  2. Parse it into a Javascript object
  3. Using it as Javascript, get the last item in the array and look at the i and addedSum values there.
  4. Create the new object you want to add to the end of the array and add it to the array
  5. Convert the modified array to JSON and write to to your file.

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);
});

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Java

Writing JSON object to a JSON file with fs.writeFileSync

From Dev

node.js fs.writeFile Not Completely Overwriting File

From Dev

Access name of file being written by fs.writeFile

From Dev

Node.js fs.writeFile() not ovewriting file

From Dev

Writing data into json file

From Dev

Prevent file corruption on exiting node in middle of fs.writeFile

From Dev

WriteFile writing filename to file

From Dev

fs writefile new line not working

From Dev

Why is the following fs.writeFile only writing data from the last file?

From Dev

node - fs.writeFile creates a blank file

From Dev

Writing to JSON file in ruby

From Dev

Why is Node fs.writeFile() method successful, but an empty file is then sent to the browser?

From Dev

Looks like when I do fs.writeFile(), the changed file restarts nodemon. How to make it not restart?

From Dev

Writing on json file with libgdx

From Dev

Writing to a JSON file

From Dev

Writing in a JSON file

From Dev

Writing data into json file

From Dev

WriteFile writing filename to file

From Dev

Writing NULL char to file in C

From Dev

fs writefile new line not working

From Dev

Running `fs.writeFile` with JSPM

From Dev

Error writing to file fs stream NodeJS

From Dev

ENOENT: no such file or directory writing file with fs

From Dev

Error with NodeJS FS (writeFile)

From Dev

trying to decode json file to variable but its only returning null

From Dev

json object returning undefined [nodejs, fs]

From Dev

Using fs.stat and fs.writeFile

From Dev

fs.writeFileSnyc/fs.writeFile writes a corrupted file

From Dev

Writing into file in nodejs using fs.writefilesync