Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing data to text file in Node.js [duplicate]

Currently, I have the following block of code:

net = require('net');
var clients = [];

net.createServer(function(s) {

  clients.push(s);

  s.on('data', function (data) {
    clients.forEach(function(c) {
      c.write(data);
    });
    process.stdout.write(data);//write data to command window
  });

  s.on('end', function() {
    process.stdout.write("lost connection");
  });

}).listen(9876);

Which is used to set up my Windows computer as a server and receive data from my linux computer. It is currently writing data to the command window. I would like to write the data into a text file to specific location, how do i do this?

like image 270
FWing Avatar asked Apr 01 '14 20:04

FWing


People also ask

How do I clone a file in node JS?

The fs. copyFile() method is used to asynchronously copy a file from the source path to destination path. By default, Node. js will overwrite the file if it already exists at the given destination.

How do you repeat a node js code?

You use repeating to print repeating strings: const repeating = require('repeating'); console. log(repeating(100, 'unicorn '));

Does FS writeFile overwrite?

fs. writeFileSync and fs. writeFile both overwrite the file by default. Therefore, we don't have to add any extra checks.


2 Answers

Use the fs module to deal with the filesystem:

var net = require('net');
var fs = require('fs');
// ...snip
s.on('data', function (data) {
  clients.forEach(function(c) {
    c.write(data);
  });

  fs.writeFile('myFile.txt', data, function(err) {
    // Deal with possible error here.
  });
});
like image 165
SomeKittens Avatar answered Sep 19 '22 10:09

SomeKittens


You should read up on the File System support in node.js.

The following method is probably the simplest way to do what you want, but it is not necessarily the most efficient, since it creates/opens, updates, and then closes the file every time.

function myWrite(data) {
    fs.appendFile('output.txt', data, function (err) {
      if (err) { /* Do whatever is appropriate if append fails*/ }
    });
}
like image 39
cybersam Avatar answered Sep 20 '22 10:09

cybersam