Learning the specifics of ES6 / NodeJS / JavaScript classes. I've created a log script which I'm passing to child_process. First, here's the logging class ./bin/log
:
'use strict';
const fs = require('fs')
const mkdirp = require('mkdirp')
module.exports = class Log {
constructor(logDir='./', name='log.log.txt', callback = ()=>{}) {
let dt = new Date()
this.dir = dt.getFullYear() + '-' + ('0' + (Number(dt.getMonth()) + 1).toString()).slice(-2) + '-' + ('0' + dt.getDate()).slice(-2)
this.filename = `${logDir}${this.dir}/${name}.${Math.round(Date.now())}.log.txt`
mkdirp(logDir + this.dir + '/', (err) => {
if (err) return callback(err);
fs.appendFile(this.filename, `${process.argv.join(' ')}\n${dt.toString()}\n`, (e) => {
if (e) return callback(e);
callback(null);
})
})
}
log(msg='') {
fs.appendFileSync(this.filename, msg.toString() + '\n');
return this;
}
err(e='') {
fs.appendFileSync(this.filename, `Error!: ${e.toString()}\n`);
return this;
}
}
So this works in my main file:
const child_process = require('child_process')
const Log = require('./bin/log')
let log = new Log('./logs/', 'KPI-Update', function(e) {
if (e) return console.error(e);
let child = child_process.spawn("Rscript", ["./bin/main.R"])
child.stderr.on("data",(d)=>{log.err(d)})
child.stdout.on("data",(d)=>{log.log(d)})
child.stdout.on("close",(d)=>{log.log(d)})
})
But this only works on the first call (on the second call, the context for this
has been changed to the child_process socket. What am I not understanding here?
child.stderr.on("data",log.err)
child.stdout.on("data",log.log)
child.stdout.on("close",log.log)
via Michael Tallino