Escribiendo archivos en Node.js


He estado tratando de encontrar una manera de escribir en un archivo cuando se utiliza Node.js, pero sin éxito. ¿Cómo puedo hacer eso?

Author: KARTHIKEYAN.A, 2010-03-23

12 answers

Hay muchos detalles en la API del sistema de archivos . La forma más común (que yo sepa) es:

var fs = require('fs');
fs.writeFile("/tmp/test", "Hey there!", function(err) {
    if(err) {
        return console.log(err);
    }

    console.log("The file was saved!");
}); 
 1888
Author: Brian McKenna,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-27 12:35:29

Actualmente hay tres formas de escribir un archivo:

  1. fs.write(fd, buffer, offset, length, position, callback)

    Debe esperar a que se realice la devolución de llamada para asegurarse de que el búfer esté escrito en el disco. No está amortiguado.

  2. fs.writeFile(filename, data, [encoding], callback)

    Todos los datos deben almacenarse al mismo tiempo; no se pueden realizar escrituras secuenciales.

  3. fs.createWriteStream(path, [options])

    Crea un WriteStream, que es conveniente porque no es necesario esperar a un callback. Pero de nuevo, no está amortiguado.

A WriteStream, como su nombre lo dice, es un arroyo. Un flujo por definición es "un búfer" que contiene datos que se mueven en una dirección (fuente ► destino). Pero un flujo de escritura no es necesariamente "buffered". Una secuencia se "almacena en búfer" cuando se escribe n veces, y en el momento n+1, la secuencia envía el búfer al núcleo (porque está lleno y necesita ser vaciado).

En otras palabras: "Un búfer" es el objeto. Si "está almacenado en búfer" o no es una propiedad de ese objeto.

Si nos fijamos en el código, el WriteStream hereda de un objeto de escritura Stream. Si prestas atención, verás cómo limpian el contenido; no tienen ningún sistema de almacenamiento en búfer.

Si escribe una cadena, se convierte en un búfer, y luego se envía a la capa nativa y se escribe en el disco. Al escribir cadenas, no están llenando ningún búfer. Entonces, si lo haces:

write("a")
write("b")
write("c")

Estás haciendo:

fs.write(new Buffer("a"))
fs.write(new Buffer("b"))
fs.write(new Buffer("c"))

Eso es tres llamadas a la capa de E/S. Aunque está utilizando "búferes", los datos no se almacenan en búfer. Un flujo en búfer haría: fs.write(new Buffer ("abc")), una llamada a la capa de E/S.

A partir de ahora, en el nodo.js v0.12 (versión estable anunciada 02/06/2015) ahora soporta dos funciones: cork() y uncork(). Parece que estas funciones finalmente le permitirán almacenar en búfer / vaciar las llamadas de escritura.

Por ejemplo, en Java hay algunas clases que proporcionar flujos en búfer(BufferedOutputStream, BufferedWriter...). Si escribe tres bytes, estos bytes se almacenarán en el búfer (memoria) en lugar de hacer una llamada de E/S solo para tres bytes. Cuando el búfer está lleno, el contenido se vacía y se guarda en el disco. Esto mejora el rendimiento.

No estoy descubriendo nada, solo recordando cómo se debe hacer un acceso a disco.

 448
Author: Gabriel Llamas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-22 21:41:46

Por supuesto, puede hacerlo un poco más avanzado. Sin bloqueo, escribiendo bits y piezas, no escribiendo todo el archivo a la vez:

var fs = require('fs');
var stream = fs.createWriteStream("my_file.txt");
stream.once('open', function(fd) {
  stream.write("My first row\n");
  stream.write("My second row\n");
  stream.end();
});
 202
Author: Fredrik Andersson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-31 17:58:37
var path = 'public/uploads/file.txt',
buffer = new Buffer("some content\n");

fs.open(path, 'w', function(err, fd) {
    if (err) {
        throw 'error opening file: ' + err;
    }

    fs.write(fd, buffer, 0, buffer.length, null, function(err) {
        if (err) throw 'error writing file: ' + err;
        fs.close(fd, function() {
            console.log('file written');
        })
    });
});
 40
Author: Mister P,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-24 09:14:21

Me gustó Índice de ./artículos/sistema de archivos.

Funcionó para mí.

Véase también Cómo escribo archivos en node.js?.

fs = require('fs');
fs.writeFile('helloworld.txt', 'Hello World!', function (err) {
    if (err) 
        return console.log(err);
    console.log('Wrote Hello World in file helloworld.txt, just check it');
});

Contenido de helloworld.txt:

Hello World!

Actualización:
Como en Linux node write en el directorio actual, parece que en algunos otros no, así que añado este comentario por si acaso :
Usando este ROOT_APP_PATH = fs.realpathSync('.'); console.log(ROOT_APP_PATH); para llegar a donde está escrito el archivo.

 22
Author: Sérgio,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-19 16:11:45

Escritura sincrónica

Fs.writeFileSync (archivo, datos[, opciones])

fs = require('fs');

fs.writeFileSync("synchronous.txt", "synchronous write!")

Escritura asíncrona

Fs.WriteFile (file, data[, options], callback)

fs = require('fs');

fs.writeFile('asynchronous.txt', 'asynchronous write!', (err) => {
  if (err) throw err;
  console.log('The file has been saved!');
});

Donde

file <string> | <Buffer> | <URL> | <integer> filename or file descriptor
data <string> | <Buffer> | <Uint8Array>
options <Object> | <string>
callback <Function>

Vale la pena leer el Sistema de Archivos oficial (fs) docs.

 8
Author: Moriarty,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-17 05:54:00
 var fs = require('fs');
 fs.writeFile(path + "\\message.txt", "Hello", function(err){
 if (err) throw err;
  console.log("success");
}); 

Por ejemplo : leer archivo y escribir en otro archivo :

  var fs = require('fs');
    var path = process.cwd();
    fs.readFile(path+"\\from.txt",function(err,data)
                {
                    if(err)
                        console.log(err)
                    else
                        {
                            fs.writeFile(path+"\\to.text",function(erro){
                                if(erro)
                                    console.log("error : "+erro);
                                else
                                    console.log("success");
                            });
                        }
                });
 5
Author: Masoud Siahkali,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-23 07:54:56

Conozco la pregunta sobre "escribir", pero en un sentido más general "anexar" podría ser útil en algunos casos, ya que es fácil de usar en un bucle para agregar texto a un archivo (ya sea que el archivo exista o no). Use un "\n " si desea agregar líneas, por ejemplo:

var fs = require('fs');
for (var i=0; i<10; i++){
    fs.appendFileSync("junk.csv", "Line:"+i+"\n");
}
 4
Author: Astra Bear,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-28 01:55:32

Aquí usamos w+ para leer/escribir ambas acciones y si no se encuentra la ruta del archivo, se creará automáticamente.

fs.open(path, 'w+', function(err, data) {
    if (err) {
        console.log("ERROR !! " + err);
    } else {
        fs.write(data, 'content', 0, 'content length', null, function(err) {
            if (err)
                console.log("ERROR !! " + err);
            fs.close(data, function() {
                console.log('written success');
            })
        });
    }
});

Contenido significa lo que tienes que escribir en el archivo y su longitud, 'contenido.longitud".

 3
Author: Gunjan Patel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-31 18:03:59

Aquí está la muestra de cómo leer archivo csv desde local y escribir archivo csv en local.

var csvjson = require('csvjson'),
    fs = require('fs'),
    mongodb = require('mongodb'),
    MongoClient = mongodb.MongoClient,
    mongoDSN = 'mongodb://localhost:27017/test',
    collection;

function uploadcsvModule(){
    var data = fs.readFileSync( '/home/limitless/Downloads/orders_sample.csv', { encoding : 'utf8'});
    var importOptions = {
        delimiter : ',', // optional 
        quote     : '"' // optional 
    },ExportOptions = {
        delimiter   : ",",
        wrap        : false
    }
    var myobj = csvjson.toSchemaObject(data, importOptions)
    var exportArr = [], importArr = [];
    myobj.forEach(d=>{
        if(d.orderId==undefined || d.orderId=='') {
            exportArr.push(d)
        } else {
            importArr.push(d)
        }
    })
    var csv = csvjson.toCSV(exportArr, ExportOptions);
    MongoClient.connect(mongoDSN, function(error, db) {
        collection = db.collection("orders")
        collection.insertMany(importArr, function(err,result){
            fs.writeFile('/home/limitless/Downloads/orders_sample1.csv', csv, { encoding : 'utf8'});
            db.close();
        });            
    })
}

uploadcsvModule()
 2
Author: KARTHIKEYAN.A,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-01 11:06:53

Puede usar la biblioteca easy-file-manager

Instale primero desde npm npm install easy-file-manager

Ejemplo, para cargar y eliminar archivos

var filemanager = require('easy-file-manager')
var path = "/public"
var filename = "test.jpg"
var data; // buffered image

filemanager.upload(path,filename,data,function(err){
    if (err) console.log(err);
});

filemanager.remove(path,"aa,filename,function(isSuccess){
    if (err) console.log(err);
});
 1
Author: Christoper,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-04 05:15:42

Puede escribir en un archivo usando el módulo fs (sistema de archivos).

Aquí hay un ejemplo de cómo puedes hacerlo:

const fs = require('fs');

const writeToFile = (fileName, callback) => {
  fs.open(fileName, 'wx', (error, fileDescriptor) => {
    if (!error && fileDescriptor) {
      // Do something with the file here ...
      fs.writeFile(fileDescriptor, newData, (error) => {
        if (!error) {
          fs.close(fileDescriptor, (error) => {
            if (!error) {
              callback(false);
            } else {
              callback('Error closing the file');
            }
          });
        } else {
          callback('Error writing to new file');
        }
      });
    } else {
      callback('Could not create new file, it may already exists');
    }
  });
};

Es posible que también desee deshacerse de esta estructura de código callback-inside-callback utilizando Promises y async/await declaraciones. Esto hará que la estructura de código asíncrona sea mucho más plana. Para hacer eso hay un útil útil.se podría utilizar la función promisify(original). Nos permite cambiar de callbacks a promesa. Echa un vistazo al ejemplo con fs funciones a continuación:

// Dependencies.
const util = require('util');
const fs = require('fs');

// Promisify "error-back" functions.
const fsOpen = util.promisify(fs.open);
const fsWrite = util.promisify(fs.writeFile);
const fsClose = util.promisify(fs.close);

// Now we may create 'async' function with 'await's.
async function doSomethingWithFile(fileName) {
  const fileDescriptor = await fsOpen(fileName, 'wx');
  
  // Do something with the file here...
  
  await fsWrite(fileDescriptor, newData);
  await fsClose(fileDescriptor);
}
 0
Author: Oleksii Trekhleb,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-20 10:36:39