99

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?

3
  • So, you want to insert a line into the middle of a text file, right? It'll be much easier to append strings to the end. Commented Oct 29, 2015 at 15:50
  • Yes, ok how can i append a string at the end ? Commented Oct 29, 2015 at 15:51
  • 1
    Possible duplicate of How to append to a file in Node? Commented Oct 29, 2015 at 16:17

5 Answers 5

225

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');
Sign up to request clarification or add additional context in comments.

6 Comments

It is necessary to save the file ? If i use fs.appendFile, the file is still empty ?
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.
Thanks for mentioning both one time and multiple time options.
does write put a new line?
This answer was for me helpful too : stackoverflow.com/a/61890003/12305715
|
9

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!');
});

Comments

5

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

Comments

4

Node.js can use streams to read data from a source and write data to a source.

Instead of read the entire contents of a file and storing it in RAM, hogging memory resources, use a stream. A stream processes data sequentially, "piece by piece", instead of all at once.

Use the fs node core module for creating a writeable stream.

const fs = require("fs");

const writeInterface = fs.createWriteStream(`${__dirname}/myTextFile.txt`, {
  flags: "a",
});

const shoppingList = [
  "dozen organic eggs",
  "oat milk",
  "cane sugar",
  "sushi rice",
  "nori",
  "sesame seeds",
  "soy sauce",
  "rice vinegar",
  "coffee",
];

shoppingList.forEach((item) => writeInterface.write(`${item}\n`));

// indicate the end of the of the writeStream with the end method
writeInterface.end();

Now the contents of myTextFile.txt are:

dozen organic eggs
oat milk
cane sugar
sushi rice
nori
sesame seeds
soy sauce
rice vinegar
coffee

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.