简体   繁体   中英

How to write function's output on multiple line in Node.JS

I want that my function write multiple lines in a text file but there is only one. I tried to make a loop but nothing changed. Please, help.

Here's my code:

const prompt = require('prompt-sync')();
const num = prompt('myquestion : ');

let path = "mypath"
var x = (Number(num));




function run() {
     for (let ligne = 0; ligne < x; ligne++) {
        fs.writeFileSync(path, "mytext");
    };
};



function gen(length) {
    var result = '';
    var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    var charactersLength = characters.length;
    for (var i = 0; i < length; i++) {
        result += characters.charAt(Math.floor(Math.random() * charactersLength));
    }
    return result;
}



run()
console.log("mytext");```

Use fs.appendFileSync instead of fs.writeFileSync ,ALSO use end of line so that cursor moves to new line while appending.Use os.EOL

var os = require("os");

    function run() {
         for (let ligne = 0; ligne < x; ligne++) {
            fs.appendFileSync(path, "mytext"+os.EOL);
        };
    };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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