NodeJS - how to write to a file all the console.log? - javascript

On my CentOS 7.x server I am running Node (v6.7.0 and v0.10.36).
forever start /home/www/html/server/mynode.js
which runs following:
/usr/bin/node /home/www/html/server/mynode.js
CODE of mynode.js:
var http = require('http');
var net = require('net');
var url = require('url');
var io = require('socket.io').listen(3004);
io.set('log level', 1);
io.sockets.on('connection', function (socket) {
socket.on('disconnect', function () {
try{
console.log(JSON.stringify(db));
} catch(dis) {
console.log(dis);
}
});
});
How do i tell NodeJS or Linux to keep log? So that i can listen whats going on by tail -f /var/log/mynode.log ?

You can overwrite your console.log
var fs = require('fs');
var trueLog = console.log;
console.log = function(msg) {
fs.appendFile("/tmp/log.log", msg, function(err) {
if(err) {
return trueLog(err);
}
});
//trueLog(msg); //uncomment if you want logs
}
Just put this snippet on top of your nodejs code.

There's an option for capturing logs
forever -o path/to/logfile start /home/www/html/server/mynode.js
From the docs -o OUTFILE Logs stdout from child script to OUTFILE

Related

issue child process inside a server on node.js

I have an executable library in C (sudo ./ads1256_test adc.txt) where data are acquired from an ADC, likewise these data are automatically save in a text file (adc.txt).
On the other hand, I have a server in node.js (see code) in which would like to execute this program when a button in the website is pressed. For this, I tried to implement this process using the child process .exec('sudo ./ads1256_test adc.txt') but it did not work. It apparently runs but the values saved in the file are always zero. That is totally different to the obtained result when I execute the same command in terminal. I would appreciate if anybody could help me.
//Importing the core modules
var express = require('express');
var path = require('path');
var sys = require('sys');
var fs = require('fs');
var util = require('util');
var sleep = require('sleep');
var app = express();
var exec = require('child_process').exec;
var spawn = require('child_process').spawn;
app.get('/', function(req,res){
res.sendFile(path.join(__dirname + '/public/index.html'));
});
//Static Directories
app.use(express.static(__dirname + '/public'));
app.post('/test', function (req, res) {
exec('sudo ./ads1256_test adc.txt');
});
//Server Starting
var server = app.listen(8080, function(err){
if(err){
console.log('Error starting http server');
} else{
console.log('Sever running at http://localhost:8080 ');
}
});
first thing first, fix your code to
- asynchronously handle the cp spawn
- show errors
Example with tree, may you adapt it to your binary and check the response, it should help you go forward.
app.post('/test', function (req, res) {
var cp = spawn('tree', []);
cp.stdout.pipe(res);
cp.stderr.pipe(res);
cp.on('close', function () {
res.end();
cp.stdout.unpipe();
cp.stderr.unpipe();
});
});

Node.js. Error: module is not a function

i have a main file -- index.js:
var express = require('express');
var app = express();
var request = require('request');
var demo = require('demo');
// This app will only respond requests to the '/scrape' URL at port 3000.
app.get('/scrape', function (req, res) {
var url = "http://www.l.com";
request(url, function (error, response, html) { // two parameters: an URL and a callback
if (!error) {
demo(html);
}
});
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
and my module is demo.js:
module.exports = function (html) {
....
return JSON.stringify(json);
}
The error is :
TypeError: demo is not a function
I am new to node.js, i would like to know why this didn't work. Maybe i dont understand the real principle of module?
Thank you for answer me first.
You're not exporting your module properly. It should be:
exports.demo = function ....
Try to include your demo module in index.js:
var demo = require('./demo.js');
For the other freshers who use module in node.js for the first time.
first, made a new module called the name of your module.js
Second, it is not necessary to do "
npm install demo --save", if you want, it is also okay.
Third, in the main js which u want to call this module, focus on the name and the path of the module, you should write var anyName = require('the name of your module');, if they are in the same directory, you should write like this: var anyName = require('./the name of your module');

How to execute command from node application

I need to call to CMD command from my node JS application ,
is it possible ?
I try with the following (POC) and I got error
var express = require('express');
var app = express();
app.get('/', function (req, res) {
function cmd_exec(cmd, args, cb_stdout, cb_end) {
var spawn = require('child_process').spawn,
child = spawn(cmd, args),
me = this;
me.exit = 0; // Send a cb to set 1 when cmd exits
child.stdout.on('data', function (data) {
cb_stdout(me, data)
});
child.stdout.on('end', function () {
cb_end(me)
});
}
foo = new cmd_exec('npm', 'install glob --save',
function (me, data) {
me.stdout += data.toString();
},
function (me) {
me.exit = 1;
}
);
setTimeout(
// wait 0.25 seconds and print the output
log_console,
250);
function log_console() {
console.log(foo.stdout);
}
res.send("Hello world");
});
I saw this code in the following link
node.js shell command execution
The error is :
TypeError: Incorrect value of args option
in line child = spawn(cmd, args),
what am I doing wrong here ?Currnlty I just use the npm install command(just for testing) but any other command that I can execute and run will be sufficient
When executing a terminal command, there are two parts: The command, and the arguments. In your case, the command is npm, and the arguments is everything that comes after that.
cmd_exec('npm', ['install', 'glob', '--save'],

Seeking Guidance on troubleshooting node memory issue

I'm trying to implement a message queue using node, socket.io, and redis. I am attempting to follow the reliable queue pattern outlined Here. I am trying to read a logfile (60M in size) in line-by-line (will be changing this later) and pump the lines into the queue for processing later. However, I am running into a memory allocation issue. I'm not sure how to troubleshoot this and would like some guidance on where to start. I can't tell if the issue is in reading the file, or in the redis client. I have been able to add messages to the queue one by one like this :
socket.emit('message', 'some sort of log line here');
Therefore I know the listener is working, but when I run the socketClient.js file It will spin out for a bit and then ultimately fail with the following generic error message:
FATAL ERROR: JS Allocation failed - process out of memory
Is there some error handling, or profiling I can add to get more information on where this is failing?
Here is the code:
socketListener.js
var util = require("util"),
redis = require("redis"),
io = require('socket.io').listen(8088)
client = redis.createClient("7777", "localhost");
util.log("Established connection to redis");
io.sockets.on('connection', function(socket) {
util.log("socket connection established for socket : " + socket);
socket.on('message', function (data) {
util.log("received the following data : ");
util.log(JSON.stringify(data, 0, 3));
client.on("error", function(err) {
util.log("Error " + err);
});
try {
// reliable queue pattern implementation
util.log("queuing up the data in the list");
client.rpush('logList', data);
client.brpoplpush('logList', 'dequeueList', 10);
} catch (err) {
util.log("An error occurred : ");
util.log(JSON.stringify(err, 0, 3));
}
});
socket.on('disconnect', function() {});
});
socketClient.js
var io = require("socket.io-client");
var socket = io.connect('http://localhost:8088');
var redis = require('redis');
var util = require('util');
var fs = require('fs');
var readline = require('readline');
socket.on('connect', function() {
client = redis.createClient("7777", "localhost");
var rd = readline.createInterface({
input: fs.createReadStream('someLogFile.log'),
terminal: false
});
rd.on('line', function(line) {
util.log("reading line " + line);
socket.emit('message', line);
});
client.lrange('dequeueList', 0, -1, function(err, results) {
if (err) {
util.log(err);
} else {
var multi = client.multi();
for (var i=0; i < results.length; i++) {
util.log('got : ' + results[i]);
multi.hgetall(results[i]);
}
multi.exec(function(err, logs) {
util.log("executing the multi commands");
util.log(JSON.stringify(logs, 0 ,3));
})
};
});
})
Thank you in advance for the help!

File transfer hangs (but without error) between node.js server and socket.io client

I want to transfer a file with node.js using socket.io (socket.io-client) and delivery.
I tried to do this on server-side:
//// server.js
var socket = require('socket.io').listen(5000);
var dl = require('delivery');
var fs = require('fs');
socket.on('connect', function() {
log( "Sockets connected" );
delivery = dl.listen(socket);
delivery.connect();
delivery.on('delivery.connect',function(delivery){
delivery.send({
name: 'file1.zip',
path : './file1.zip'
});
delivery.on('send.success',function(file){
console.log('File sent successfully!');
});
});
});
And this on client-side:
//// client.js
var io = require('socket.io-client');
var dl = require('delivery');
var fs = require('fs');
var socket = io.connect('http://localhost:5000');
socket.on('connection', function(socket){
var delivery = dl.listen(socket);
delivery.on('receive.success',function(file){
fs.writeFile(file.name, file.buffer, function(err) {
if(err) {
console.log('File could not be saved: ' + err);
} else {
console.log('File ' + file.name + " saved");
};
});
});
});
On execution, there is no error, but it hangs.
Server-side:
$ node server.js
info - socket.io started
debug - client authorized
info - handshake authorized Bbzo928wAyTjDX8v06Ic
debug - setting request GET /socket.io/1/websocket/Bbzo928wAyTjDX8v06Ic
debug - set heartbeat interval for client Bbzo928wAyTjDX8v06Ic
debug - client authorized for
debug - websocket writing 1::
debug - emitting heartbeat for client Bbzo928wAyTjDX8v06Ic
debug - websocket writing 2::
debug - set heartbeat timeout for client Bbzo928wAyTjDX8v06Ic
debug - got heartbeat packet
debug - cleared heartbeat timeout for client Bbzo928wAyTjDX8v06Ic
debug - set heartbeat interval for client Bbzo928wAyTjDX8v06Ic
And on client-side there is no output:
$ node client.js
Do anyone know, what goes wrong?
First of all, the version of delivery in the NPM repository is out of date, and contains some bugs. You should install the latest version from GitHub:
$ npm install git+https://github.com/liamks/Delivery.js.git
Next, you're mixing up some client and server parts, specifically the events that each has to handle. This (somewhat, see below) works for me:
//// server.js
var io = require('socket.io').listen(5000);
var dl = require('delivery');
var fs = require('fs');
io.sockets.on('connection', function(socket) {
console.log('server: a new client connected');
var delivery = dl.listen(socket);
delivery.on('delivery.connect', function(delivery) {
delivery.send({
name: 'file1.zip',
path : './file1.zip'
});
delivery.on('send.success', function(file) {
console.log('File sent successfully!');
});
});
});
//// client.js
var io = require('socket.io-client');
var dl = require('delivery');
var fs = require('fs');
var socket = io.connect('http://localhost:5000');
socket.on('connect', function() {
console.log('client: connected to server');
var delivery = dl.listen(socket);
delivery.connect();
delivery.on('receive.success', function(file) {
// TODO: fs.writeFile(...);
});
});
However, it seems that the receive.success event is delivered to the client twice, at least for me. I'm not sure why (I'm not overly familiar with delivery).

Categories