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')
CodePudding user response:
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;
});
CodePudding user response:
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();
CodePudding user response:
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;
});