Nodejs append to file new line

I'm trying to Append data to a Log file using Node.js and that is working fine but it is not going to the next line. \n doesn't seem to be working in my function below. Any suggestions?

function processInput ( text ) 
{     
  fs.open('H://log.txt', 'a', 666, function( e, id ) {
   fs.write( id, text + "\n", null, 'utf8', function(){
    fs.close(id, function(){
     console.log('file is updated');
    });
   });
  });
 }

buydadip

8,42020 gold badges73 silver badges144 bronze badges

asked Apr 30, 2012 at 13:15

1

It looks like you're running this on Windows (given your H://log.txt file path).

Try using \r\n instead of just \n.

Honestly, \n is fine; you're probably viewing the log file in notepad or something else that doesn't render non-Windows newlines. Try opening it in a different viewer/editor (e.g. Wordpad).

answered Apr 30, 2012 at 13:17

Rob HruskaRob Hruska

116k30 gold badges165 silver badges190 bronze badges

2

Use the os.EOL constant instead.

var os = require("os");

function processInput ( text ) 
{     
  fs.open('H://log.txt', 'a', 666, function( e, id ) {
   fs.write( id, text + os.EOL, null, 'utf8', function(){
    fs.close(id, function(){
     console.log('file is updated');
    });
   });
  });
 }

answered Sep 18, 2015 at 18:29

shinzoshinzo

1,2091 gold badge8 silver badges2 bronze badges

7

use \r\n combination to append a new line in node js

  var stream = fs.createWriteStream("udp-stream.log", {'flags': 'a'});
  stream.once('open', function(fd) {
    stream.write(msg+"\r\n");
  });

answered Aug 29, 2020 at 5:36

Nodejs append to file new line

CodemakerCodemaker

9,2793 gold badges66 silver badges60 bronze badges

Alternatively, you can use fs.appendFile method

let content = 'some text';
content += "\n";
fs.appendFile("helloworld.txt", content, (err) => {
    return console.log(err);
});

answered Dec 27, 2021 at 10:57

hamonhamon

532 silver badges9 bronze badges

1

NodeJS offers many powerful ways to work with files. Sometimes you may need to do simple things like appending new line to file in NodeJS. In this article, we will look at how to append file in NodeJS, synchronously, asynchronously and as a stream.

Let us assume that you have a text file at /home/ubuntu/data.txt. Here are the two ways to append new line to file in NodeJS. For both these methods, we will use fs node package which offers many useful methods to work with files.

1. Synchronous File Append

In this case we will use appendFileSync method to synchronously update files. Here you need to specify the full path to your file, and the text to be appended. Here is its syntax.

fs.appendFileSync( path, data )

Here is an example.

const fs = require('fs');
fs.appendFileSync('/home/ubuntu/data.txt', 'test new line');

Since the above method is synchronous, it will block the execution cycle till file append is complete. Synchronous file update is useful in case the subsequent lines of code depend on the latest information in your file.

2. Asynchronous File Append

In this cases, we use appendFile method to add new line of text asynchronously. Here is its syntax.

fs.appendFile( path, data[, options], callback )

Here is an example.

const fs = require('fs');
fs.appendFile('/home/ubuntu/data.txt', 'test new line', function (err) {
  if (err) throw err;
  console.log('New line added');
});

In case of asynchronous file append, the control will be returned back to the main execution thread, that is, subsequent lines of code will continue to be executed without waiting for the file append to be completed. This is useful if subsequent code does not depend on the latest information present in your file.

It is important to note that appendFile opens a new file handle every time you can call it. So it is useful if you want to update your file occassionally. However, you should avoid using it for frequent file updates such as log update, or call it in a loop.

In such cases, you must use fs.WriteStream() function as shown below.

3. Using WriteStream

WriteStream uses the same file handler to make multiple updates. It is a great way to continuously write to files, without running out of memory. Here is an example.

var stream = fs.createWriteStream("/home/ubuntu/data.txt", {flags:'a'});

[...Array(10000)].forEach( function (item,index) {
    stream.write(index + "\n");
});

stream.end();

In the above code we are simply looping from 1 to 10000 and appending the integers one by one to our file. In the first line, we create a stream. Next, we use it in a loop to write the loop index value in each iteration. Finally we close the stream with stream.end() function.

In this article, we have seen both synchronous and asynchronous ways to append file in NodeJS. We have also looked at how to append file as a stream.

Also read:

How to Run NodeJS App in Background
How to Fix NGINX Upstream Timed Out Error
How to Fix EADDRINUSE Error in NodeJS
How to Prevent Direct File Access in PHP
How to Enable ES6 Import in NodeJS

How do I add a new line in Nodejs?

Try using \r\n instead of just \n. \n is fine; you're probably viewing the log file in notepad or something else that doesn't render non-Windows newlines. Try opening it in a different viewer/editor (e.g. Wordpad).

How do I append a file in node JS?

To append data to file in Node. js, use Node FS appendFile() function for asynchronous file operation or Node FS appendFileSync() function for synchronous file operation.

What is the difference between writeFile and appendFile?

writeFile with the filename, and data to write to that file (as a string or a buffer). That will overwrite the entire file, so to just append that data to the file instead, pass an options object with the flag key set to a . Or, you can use fs. appendFile .

What is true about appendFile function of FS module?

The fs. appendFile() method is used to asynchronously append the given data to a file. A new file is created if it does not exist. The options parameter can be used to modify the behavior of the operation.