NodeJS Agent similar to Java agent - node.js

I am trying to create node agent similar to java agent to gather the performance of running nodejs application
I found appmetrics npm package and it works fine , if I include that to the exisitng nodejs script but I am trying to run as an agent without modifying existing nodejs script
Sample which explains my issue which works fine
var http = require("http");
var appmetrics = require('appmetrics');
var monitoring = appmetrics.monitor();
http.createServer(function (request, response) {
// Send the HTTP header
// HTTP Status: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/plain'});
// Send the response body as "Hello World"
response.end('Hello World\n');
}).listen(8083);
// Console will print the message
console.log('Server running at http://127.0.0.1:8083/');
monitoring.on('initialized', function (env) {
env = monitoring.getEnvironment();
for (var entry in env) {
console.log(entry + ':' + env[entry]);
};
});
monitoring.on('cpu', function (cpu) {
console.log('[' + new Date(cpu.time) + '] CPU: ' + cpu.process);
});
Issue is to have appmetric separately and nodejs hello world script separately and running them together
helloworld.js
var http = require("http");
http.createServer(function (request, response) {
// Send the HTTP header
// HTTP Status: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/plain'});
// Send the response body as "Hello World"
response.end('Hello World\n');
}).listen(8083);
// Console will print the message
console.log('Server running at http://127.0.0.1:8083/');
monitor.js
var appmetrics = require('appmetrics');
var monitoring = appmetrics.monitor();
monitoring.on('initialized', function (env) {
env = monitoring.getEnvironment();
for (var entry in env) {
console.log(entry + ':' + env[entry]);
};
});
monitoring.on('cpu', function (cpu) {
console.log('[' + new Date(cpu.time) + '] CPU: ' + cpu.process);
});
Trying to run above mentioned two scripts at a time using
node which is not working
node helloworld.js && node monitor.js

Related

How is Nuxtjs started on openlitespeed with Nodejs? Startup file example

Trying to upload my project to openlitespeed. However, encountering difficulties.
Basic Node setup is that:
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World form node js app.js\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
Have a look at how to include Modules as below:
var http = require('http');
var dt = require('./myfirstmodule');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write("The date and time are currently: " + dt.myDateTime());
res.end();
}).listen(8080);
But, I can basicly run my Nuxtjs project on local host.
What is the possible expected result:
Running Nuxtjs application on VPS which is upcloud with a startup file for having seen serving it on openlitespeed.
Have checked here, but no info on openlitespeeed deployment: https://nuxtjs.org/docs/2.x/deployment/nginx-proxy
Hi it was pretty easy after some research:
https://nuxtjs.org/docs/2.x/deployment/deployment-pm2
copy this file named ecosystem.config.js file in which it has these codes to Root folder of Nuxt:
module.exports = {
apps: [
{
name: 'NuxtAppName',
exec_mode: 'cluster',
instances: 'max', // Or a number of instances
script: './node_modules/nuxt/bin/nuxt.js',
args: 'start'
}
]
}
Run on your linux:
killall node
cd /usr/local/lsws/serverclient/client
pm2 start
Good to go

Does starting a server at localhost:8081 creates internet connection issues?

I have started a server at local host:8081 as
var http = require("http");
http.createServer(function (request, response) {
// Send the HTTP header
// HTTP Status: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/plain'});
// Send the response body as "Hello World"
response.end('Hello World\n');
}).listen(8081);
// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');
After starting the service, I am not able to access internet. please help me with this.

NodeJS run server for receiving POST and serve GET

1) Running a NodeJS server on localmachine
2) One device with App making a POST req to Node server.
3) XAMPP page making a GET request to get what device (from point 2) sent to Node server.
hope that's clear.
this is what I have, but GET receives undefined.
POST logs key1=value1
var http = require('http');
http.createServer(function (req, res) {
console.log(req.method);
var txt;
if(req.method == "POST") {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
var url = require("url"),
parsedUrl = url.parse(req.url, false), // true to get query as object
queryAsObject = parsedUrl.query;
txt = JSON.stringify(queryAsObject);
console.log(txt);
} else {
// for GET requests, serve up the contents in 'index.html'
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('Hello Worldzz\n'); // I WANT TO PASS txt here.
console.log("jaa" + txt);
}
}).listen(1337, 'my.ip.here');
console.log('Server running at http://my.ip.here:1337/');
-- update. CHECKing
function checkServer() {
$.ajax({
type: "GET",
url: "http://my.ip.here:1337/",
async: false,
}).success(function( text ) {
console.log("res" + text);
$( "h2" ).text( text );
});
}
This is just a simple scope problem. Since you want all requests to share the same txt var, you'll need to define txt in a place where all requests can access it.
var http = require('http');
var txt;
http.createServer(function (req, res) {
console.log(req.method);
//var txt;

How to End HTTP Response body in node.js

I have created a web server which shows the directory and file listing by firing ls -l. As i am new to node.js environment, I don't know how to end HTTP Body Response for async code.
Following is my code-
var terminal = require('child_process').spawn('bash');
var http = require('http');
var s = http.createServer(function (req, res) {
res.writeHead(200, {'content-type': 'text/plain'});
terminal.stdout.on('data', function (data) {
res.write('stdout: ' + data);
});
setTimeout(function () {
res.write('Sending stdin to terminal');
terminal.stdin.write('ls -l\n');
res.write('Ending terminal session');
terminal.stdin.end();
}, 1000);
terminal.on('exit', function (code) {
res.write('child process exited with code ' + code + '\n');
res.end("Response Ended");
});
});
s.listen(8000);
This code works fine for serving first request. But while serving second request there is an error: "write after end".
Why is this happening? How can i rectify this?
You're only spawning a process once (before the server starts), so once that process has exited, you cannot write to it anymore. Try this instead:
var http = require('http'),
spawn = require('child_process').spawn;
var s = http.createServer(function (req, res) {
var terminal = spawn('bash');
res.writeHead(200, {'content-type': 'text/plain'});
terminal.stdout.on('data', function (data) {
res.write('stdout: ' + data);
});
setTimeout(function () {
res.write('Sending stdin to terminal');
terminal.stdin.write('ls -l\n');
res.write('Ending terminal session');
terminal.stdin.end();
}, 1000);
terminal.on('exit', function (code) {
res.write('child process exited with code ' + code + '\n');
res.end("Response Ended");
});
});
s.listen(8000);

Unable to set headers in node.js in POST method

I have a case where i have to read the data from the request body and create a file and write the data into it. If the operation is successful I set the response header to 201 and add the location of file in Location header. The file creation is done using Java methods and node.js code is below.
var server = http.createServer(function(req, res)
{
var body = "";
req.on("data", function(chunk)
{
body += chunk.toString();
});
req.on("end", function() {
var rtn = obj.AddonPostMethod(filepath,body);
if(rtn.length < 13)
{
res.writeHead(201, {"Location" : rtn});
res.end();
}
else
{
res.writeHead(400, {"Content-Type" : application/json"});
res.write(''+rtn);
res.end();
}
});
}});
The problem is that the response headers are not getting updated and are always set to the default headers 200 Ok. In addition to this the server is always busy even after the response is received.
I don't think you're actually listening on a port with the code you reference.
var http = require('http');
http.createServer(function(req,res){
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(8000);
console.log('Server running at http://127.0.0.1:8000/');
You never declare the http object as actually listening on a port/ip with the .listen() function.
Also, you don't need to wait for the req object to emit anything to respond. The function is called when the request is complete. You can listen for specific requests and route them appopriately by storing the http.Server object to a variable.
var server = http.createServer();
server.listen(8000);
server.on('request', function(req,res){ /* do something with the request */ });
More documentation on the http object can be found on the node.js documents for http

Resources