rez
rez

Reputation: 331

Printing numbers from 1-100 then storing it in a txt file

So I made a simple code to print numbers from 1 to 100 and it works just fine, but I want to store every number in a text file, so every number from 1 to 100 would be stored in its own line, Issue I have is that its only storing the last number

const fs = require('fs')

for(var i = 1; i < 100; i++){
let data = `(1, ${i}, 0, 'Game Channel ${i}', '1'),`

fs.writeFile('Output.txt', data, (err) => {
    if (err) throw err;
})}

For example in txt file output would be:

(1, 1, 0, 'Game Channel 1', '1'),
(1, 2, 0, 'Game Channel 2', '1')

Upvotes: 0

Views: 582

Answers (3)

Siva Kondapi Venkata
Siva Kondapi Venkata

Reputation: 11011

First build whole combined string and then write to file.

const fs = require('fs');

const data = Array.from({length: 100}, (_, i) => `(1, ${i+1}, 0, 'Game Channel ${i+1}', '1'),\n`).join('')

fs.writeFile('Output.txt', data, (err) => {
    if (err) throw err;
});

Upvotes: 0

Wyck
Wyck

Reputation: 11760

You can use createWriteStream to open the file, and then write to it asynchronously.

const fs = require('fs');

async function main() {
  const ws = fs.createWriteStream('output.txt');
  for (let i = 1; i < 100; i++) {
    let data = `(1, ${i}, 0, 'Game Channel ${i}', '1'),\n`
    await ws.write(data);
  }
}
main();

Upvotes: 0

Samathingamajig
Samathingamajig

Reputation: 13283

Write at the end, since you're be overwriting it on every subsequent write.

const fs = require('fs');

let data = "";

for (let i = 1; i <= 100; i++){
    data += `(1, ${i}, 0, 'Game Channel ${i}', '1'),\n`;
}

fs.writeFile('Output.txt', data, (err) => {
    if (err) throw err;
});

Upvotes: 1

Related Questions