0

Can someone give me a hand with converting the following code from console output to file output? I'm struggling with logging and the asynchronous nature of Node. The script works great in a console, but I'd like to pipe the sorted output into individual server sections within a file with STDERR going to another file.

var rexec = require('remote-exec');
var fs = require('fs');
var lineReader = require('line-reader');
var streamBuffers = require('stream-buffers');

var _ = require('lodash');

var conn_options = {
  port: 22,
  username: '*****',
  privateKey: fs.readFileSync('R:/nodeJS/sshkey.priv')
}

// something that dumps out a bunch of data...
var cmds = ['df']
var filename = 'servers.txt';

lineReader.eachLine(filename,function(line,last,cb){

    var buffer = new streamBuffers.WritableStreamBuffer();

    var my_conn_options = _.clone(conn_options);


    rexec(line,cmds,my_conn_options,function(err){
        if (err) {
            console.log(line, err);
        } else {
            console.log('>>>> Start: ' + line + '<<<<')
            console.log(buffer.getContentsAsString());
            console.log('>>>> End: ' + line + '<<<<')
        };

    });
    if (last) {
        cb(false); // stop reading
    } else {
        cb();
    }
}); 

1 Answer 1

1

check this example, that should help..

var fs = require('fs');
var util = require('util');
var logFile = fs.createWriteStream('log.txt', { flags: 'a' });
  // Or 'w' to truncate the file every time the process starts.
var logStdout = process.stdout;

console.log = function () {
  logFile.write(util.format.apply(null, arguments) + '\n');
  logStdout.write(util.format.apply(null, arguments) + '\n');
}
console.error = console.log;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.