Write in a txt file

4

What I want is to add "a line of text" every time the code is executed. However what I get is to replace all the content of the txt. I leave my code here.

const fs = require("fs");
let ruta = './log.txt'
let texto = "Esto es una prueba \n\t";
fs.open(ruta, 'w+', (err, fd) => {
    if (err) { 
        console.log(err); 
    }
    else {        
        fs.appendFile(ruta, texto, function (err) {
            if (err) throw err;
            fs.close(log, function (err) {
                if (err) throw err;
                console.log('It\'s saved!');
            });
        });
    }
});
    
asked by Jose Sotteccani 21.12.2018 в 16:52
source

1 answer

3

If you look at the fs.open() documentation, you'll see the flags that are available are:

  

'w+' - Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists) .

     

'a' - Open file for appending . The file is created if it does not exist.

Translation:

'w+' : Opens in read and write mode. Create the file if it does not exist and if it exists it truncates it (deletes all its contents).

'a' : Open the file to add. If the file does not exist, it is created.

So your problem is that you are deleting the contents of the file every time you open it, you must change the flag by 'a' (I take the opportunity to fix a couple of bugs that you have the code, see my comments:

const fs = require("fs");
let ruta = './log.txt'
let texto = "Esto es una prueba \n\t";
fs.open(ruta, 'a', (err, fd) => {
    if (err) { 
        console.log(err); 
    }
    else {
        //si tienes ya el fd (file descriptor), usémoslo        
        fs.appendFile(fd, texto, function (err) {
            if (err) throw err;
            //de nuevo, usemos el fd para cerrar el fichero abierto
            fs.close(fd, function (err) {
                if (err) throw err;
                console.log('It\'s saved!');
            });
        });
    }
});

Anyway, if you just want to write, you do not need to open the file before, if you pass the path to appendFile as a string, open and close the file automatically, simplifying the code:

const fs = require("fs");
let ruta = './log.txt'
let texto = "Esto es una prueba \n\t";
fs.appendFile(ruta, texto, function (err) {
  if (err) throw err;
});
    
answered by 21.12.2018 / 17:12
source