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

node.jsFs

node.js Problem Overview


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?

node.js Solutions


Solution 1 - node.js

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 - node.js

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 - node.js

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

Solution 4 - node.js

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);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMeterionView Question on Stackoverflow
Solution 1 - node.jsLeonid BeschastnyView Answer on Stackoverflow
Solution 2 - node.jsmichelemView Answer on Stackoverflow
Solution 3 - node.jsYene MulatuView Answer on Stackoverflow
Solution 4 - node.jsISURU THIWANKAView Answer on Stackoverflow