How to create and write data into a txt text file in Nodejs?

Jul 01 2021 29

Hi there, I'm a newbie in Nodejs. 

I have a small project with Node and I want to load data from a database and save it into a .txt text file.

My version of Nodejs is v12.18.3

I've been trying to find some ways to write to a file but with no success. How can I do that?

Have 3 answer(s) found.
  • d

    dang nhat hai long Jul 01 2021

    We have many ways to create and write data in a txt file. I usually:

     const fs = require('fs');
    fs.writeFileSync('/tmp/file_name.txt', 'Hey txt file!');

    you also write with non-async:

     const fs = require('fs');
    fs.writeFile("/tmp/file_name.txt", "Test txt file", function(err) {
        if(err) {
            return console.log(err);
        }
        console.log("Your file was saved!");
    }); 

    I hope it helpful for you!!!

  • V

    Víctor Vázquez Jul 01 2021

    You can use way below, It's non-blocking, writing bits and pieces, not writing the whole file at once:

     var fs = require('fs');
    var stream = fs.createWriteStream("your_file.txt");
    stream.once('open', function(fd) {
      stream.write("Line data 1 \n");
      stream.write("Line data 2\n");
      stream.write("Line data 3\n");
      stream.end();
    });

    And it works for me!

  • M

    Minh Vĩnh Jul 01 2021

    You can try with some lines of code as below:

     fs = require('fs');
    fs.writeFile('helloworld.txt', 'Hello World!', function (err) {
        if (err) 
            return console.log(err);
        console.log('Wrote Hello World in file helloworld.txt');
    });

    And now you can open file txt and check it!!!

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close