Writing data to a text file in Node.js

I currently have the following 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);

Used to configure my Windows computer as a server and receive data from my Linux computer. He is currently writing data to the command window. I would like to write data to a text file in a specific place, how to do it?

+4
source share
2 answers

Use the module fsto work with the file system:

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.
  });
});
+2
source

You should read the file system support in node.js.

- , , , , , /, .

function myWrite(data) {
    fs.appendFile('output.txt', data, function (err) {
      if (err) { /* Do whatever is appropriate if append fails*/ }
    });
}
+4

Source: https://habr.com/ru/post/1534526/


All Articles