7

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?

3
  • Note that Java is not the same as JavaScript; Node.js is server-side JavaScript. Commented Apr 1, 2014 at 20:07
  • thats why i said in newbie on this, i know nth abt java :( Commented Apr 1, 2014 at 20:08
  • Fortunately the language you are working in is JavaScript, you don't need to know anything about Java. Commented Apr 1, 2014 at 20:10

2 Answers 2

6

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.
  });
});
Sign up to request clarification or add additional context in comments.

5 Comments

By default, writeFile() will overwrite anything that was already in the file, so this answer will only leave the last 'data' item in the file.
well, this exactly wt i want to do, over write the data, and leave the latest data in the text file only.
However, the problem I am having at the moment is, I dont have any error, but i cant file the .txt file even with the search function of windows :/
@FWing The txt file should be in the directory where you ran node
oh alrite, thank you, i got it, not sure why the search function doesnt work
4

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*/ }
    });
}

6 Comments

is it a must that i hv to be prepare when i encounter an error? i have no idea wt to do?
You could just output an error to the console, if you don't know what else to do. For example: console.error("Failed to output data. Data: %s, Error: %s", data, err);
same problem here, i dont hv any error, but i couldnt find my file, im not sure if the code is working
You can explicitly specify the full path for the file, so that you know where it goes.
yes, i made it, thank you very much!
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.