Skip to content
Advertisement

fs.writeFileSync method writing wrong to a text file

I have a problem with my script related to writing to a text file.

The logic flow works as follows: I read an entire unformatted text file with fs.readFileSync and pass all the read content to a variable of type string. After that I use the .split to break this text into several parts and keep each part of the broken text in an array. After that I use a for loop to go through this array and write to another text file, but here’s the problem, I don’t know if the information flow is too fast in the loop, which is sometimes written to this text file in a messy way, not respecting the order of the array being read.

Here is the code:

try{
    const data = fs.readFileSync('test_zpl.txt', 'utf8')
    txt = data.replace(/s/g,"");
} catch (err) {
    console.log(err);
}

ArrayZPL = txt.split("+");

//Writting
for(i=0;i<ArrayZPL.length;i++){

    try{
        fs.writeFileSync('zpl_text.txt', ArrayZPL[i]);
    } catch (err){
        console.log(err);
    }

}

//Reading
try{
    const data = fs.readFileSync('zpl_text.txt', 'utf8')
    zpl = data;
} catch (err) {
    console.log(err);
}

Advertisement

Answer

fs.writeFileSync overwrites the file path passed as its first parameter. For a demonstration run the code below in node, type the contents of test.txt in the working directory on the console and repeat:

const fs = require("fs");
const path = require("path");
const filepath = path.resolve("./test.txt");

let string = "random-" + Math.random();
console.log( "writing %s to %s", string, filepath);
fs.writeFileSync( filepath, string);

To write the file in chunks you could create a writable stream and write array entries in chunks using asynchronous code. To maintain synchronous code, join array entries and write the result:

fs.writeFileSync('zpl_text.txt', ArrayZPL.join("");
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement