Write a line into a .txt file with Node.js

151,325

Solution 1

Inserting data into the middle of a text file is not a simple task. If possible, you should append it to the end of your file.

The easiest way to append data some text file is to use build-in fs.appendFile(filename, data[, options], callback) function from fs module:

var fs = require('fs')
fs.appendFile('log.txt', 'new data', function (err) {
  if (err) {
    // append failed
  } else {
    // done
  }
})

But if you want to write data to log file several times, then it'll be best to use fs.createWriteStream(path[, options]) function instead:

var fs = require('fs')
var logger = fs.createWriteStream('log.txt', {
  flags: 'a' // 'a' means appending (old data will be preserved)
})

logger.write('some data') // append string to your file
logger.write('more data') // again
logger.write('and more') // again

Node will keep appending new data to your file every time you'll call .write, until your application will be closed, or until you'll manually close the stream calling .end:

logger.end() // close string

Note that logger.write in the above example does not write to a new line. To write data to a new line:

var writeLine = (line) => logger.write(`\n${line}`);
writeLine('Data written to a new line');

Solution 2

Simply use fs module and something like this:

fs.appendFile('server.log', 'string to append', function (err) {
   if (err) return console.log(err);
   console.log('Appended!');
});

Solution 3

I created a log file which prints data into text file using "Winston" logger. The source code is here below,

const { createLogger, format, transports } = require('winston');
var fs = require('fs')
var logger = fs.createWriteStream('Data Log.txt', {
  flags: 'a' 
})
const os = require('os');
var sleep = require('system-sleep');
var endOfLine = require('os').EOL;
var t = '             ';
var s = '         ';
var q = '               ';
var array1=[];
var array2=[];
var array3=[];
var array4=[];
              
array1[0]  =  78;
array1[1]  =  56;
array1[2]  =  24;
array1[3]  =  34;
                  
for (var n=0;n<4;n++)
{
  array2[n]=array1[n].toString();
}
                 
for (var k=0;k<4;k++)
{
  array3[k]=Buffer.from('                    ');
}

for (var a=0;a<4;a++)  
{
  array4[a]=Buffer.from(array2[a]);
}

for (m=0;m<4;m++)
{
  array4[m].copy(array3[m],0);
}

logger.write('Date'+q);
logger.write('Time'+(q+'  '))
logger.write('Data 01'+t);
logger.write('Data 02'+t); 
logger.write('Data 03'+t);
logger.write('Data 04'+t)

logger.write(endOfLine);
logger.write(endOfLine);

function mydata()      //user defined function
{
  logger.write(datechar+s);
  logger.write(timechar+s);
  for ( n = 0; n < 4; n++) 
  {
   logger.write(array3[n]);
  }
  logger.write(endOfLine); 
}

var now = new Date();
var dateFormat = require('dateformat');
var date = dateFormat(now,"isoDate");
var time = dateFormat(now, "h:MM:ss TT ");
var datechar = date.toString();
var timechar = time.toString();
mydata();
sleep(5*1000);

Solution 4

Step 1

If you have a small file Read all the file data in to memory

Step 2

Convert file data string into Array

Step 3

Search the array to find a location where you want to insert the text

Step 4

Once you have the location insert your text

yourArray.splice(index,0,"new added test");

Step 5

convert your array to string

yourArray.join("");

Step 6

write your file like so

fs.createWriteStream(yourArray);

This is not advised if your file is too big

Share:
151,325
Meterion
Author by

Meterion

Updated on July 05, 2022

Comments

  • Meterion
    Meterion about 2 years

    I want to use Node.js to create a simple logging system which prints a line before the past line into a .txt file. However, I don't know how the file system functionality from Node.js works.

    Can someone explain it?

  • Meterion
    Meterion over 8 years
    It is necessary to save the file ? If i use fs.appendFile, the file is still empty ?
  • Leonid Beschastny
    Leonid Beschastny over 8 years
    appendFile will open text file, append new data to it, and save it afterwards. So, no, you don't need to save it yourself. It your file is empty, try checking err in appendFile callback.
  • Tomáš Zato
    Tomáš Zato about 7 years
    Thanks for mentioning both one time and multiple time options.
  • theonlygusti
    theonlygusti about 5 years
    does write put a new line?
  • Akshay Hazari
    Akshay Hazari almost 4 years
    Why is logger.write (for second example) consuming large heap space while writing a huge file?
  • zerbene
    zerbene over 3 years
    This answer was for me helpful too : stackoverflow.com/a/61890003/12305715