Node.JS - 想要将控制台上的输出移动到log / err文件中

时间:2016-08-24 16:18:26

标签: javascript node.js

有人可以帮助我将以下代码从控制台输出转换为文件输出吗?我正在努力解决日志记录和Node的异步性问题。该脚本在控制台中运行良好,但是我希望将已排序的输出通过STDERR传输到另一个文件中的文件中的各个服务器部分。

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 个答案:

答案 0 :(得分:1)

检查这个例子,这应该有帮助..

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;