data exchange via localhost in node.js - node.js

in the following code, app1.js sends information on localhost port 3000
//app1.js
var http = require('http');
const valueToTransfert = 'test';
var server = http.createServer(function(req, res) {
res.end('valueToTransfert');
});
server.listen(3000);
I want to make a second program app2.js that will run simultaneously and read data sent by app1.js on localhost:3000.
How can I do that ?
Thank you for your help

This is a bit of a hack but it might work your your immediate purposes
require('child_process').exec('node app2.js test', function(err, stdout, stderr) {
// you get your results in stdout
// app2.js would have to output its result with console.log(...);
});
But if you need to send more data you will probably have to setup another server, or do something a bit more complex.

Related

Node index.js command is keep ignored in window powershell

I'm trying to run index.js in localhost.
So, I make index.js like this.
const http = require('http');
http.createServer((req, res) => {
res.end('Hello');
}).listen(3000, ()=> {
console.log('running');
})
I typed node index.js but there is nothing in the console and it just turns off by itself.
There is nothing on console.
like this.
I typed that thing at PowerShell and git bash but none of them works.
I tried another port like 8080 or 8000 but it's not working.
And I also used forever, pm2, and nodemon but it doesn't work, too.
I think it's something like a firewall problem.
But I don't know what's wrong.
Try to break your code.
It might be because your code does not hold the instance of the server, it clear itself ... hence the listen promise isn't even reached.
const http = require('http');
const server = http.createServer((req, res) => {
res.end('Hello');
})
server.listen(3000, ()=> {
console.log('running');
})
## Try below code please
var http = require('http');
//create a server object:
http.createServer(function (req, res) {
res.write('Hello World!'); //write a response to the client
res.end(); //end the response
}).listen(8080); //the server object listens on port 8080

This node js code doenot result anything

var http = require('http');
var server = http.createServer(function(req, res) {
res.writeHead(200);
res.end('Hello Http');
});
server.listen(8080);
I am not getting result for the above nodejs code i am executing the code like this node hw.js from git bash
I am new to nodejs
Your code is creating an HTTP server on port 8080.
For every request it will respond with 'Hello Http'
Try opening http://localhost:8080/ in your browser and you will see it.

Socket io on connection not connecting NodeJS

I just started learning NodeJS and I am trying to make a simple server-client project using Socket io.
What happens right now is that when I open localhost:8001, I don't see any logs inside the listener.sockets.on block.
var http = require('http');
var app = http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('<h1>Hello!</h1>');
}).listen(8001);
var io = require('socket.io');
var listener = io.listen(app);
console.log("Sample Socket IO");
listener.sockets.on('connection', function (socket) {
console.log('a user connected');
socket.emit('connected', 'Welcome');
socket.on('disconnect', function () {
console.log('user disconnected');
});
});
It looks like the logging will occur when a connection happens. You setup a listening socket, so try to connect to it. Try 'telnet 127.0.0.1 8001' to connect.
The browser page needs to load the socket.io client code for one thing. That is the first thing missing that I can see. Look through the example here http://socket.io/get-started/chat/ and make sure you are following exactly at first and then make changes after you get that example working. Your server code looks a bit different from their example also.

connect cmd line socket server via nodejs socket.io

I have a node.js server communicating to a client web page, sending it message. This is working great based on the many tutorials and searching stack overflow :)
Where I am having an issue is when I attempt to startup a separate socket connection to a 3rd party cmd line executable instance runs as a socket server. The 3rd party executable does not adhere to the socket.io namespace/room type of events, so I read that socket.io-events may help where instead of:
socket.on('some key', function(){/**do stuff*/}); I could:
eventRouter.on('*', function(){/*do stuff*/});
For this communication, I am assuming I need to use socket.io-client on the node.js side in order to talk to the cmd executable, but I am getting exceptions trying to do a socket2.use(router); where socket2 is my socket.io-client and router is the socket.io-events object.
All runs on localhost, node to web page is port 8001 and node.js to executable is on port 8002. Please pardon the code, for I have been trying to get this to work for a few days and is a bit ugly now.
The cmd executable to execute and its arguments I have coming from the web page which works. I am able to start the exe. The EXE expects a ACK on each message sent, thus why you see the code emitting it back.
I have a interval where I set and update an element on the web page. I have another element that I set messages (msg).
var http = require('http');
var url = require('url');
var fs = require('fs');
var server;
server = http.createServer(function(req, res){
// your normal server code
var path = url.parse(req.url).pathname;
switch (path){
case '/':
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<h1>Hello! Try the Test page </h1>');
res.end();
break;
case '/socket.html':
fs.readFile(__dirname + path, function(err, data){
if (err){
return send404(res);
}
res.writeHead(200, {'Content-Type': path == 'json.js' ? 'text/javascript' : 'text/html'});
res.write(data, 'utf8');
res.end();
});
break;
default: send404(res);
}
}),
send404 = function(res){
res.writeHead(404);
res.write('404');
res.end();
};
server.listen(8001);
var str = "ack0";
var bytes = [];
for (var i = 0; i < str.length; ++i) {
bytes.push(str.charCodeAt(i));
}
// use socket.io
var io = require('socket.io').listen(server);
// define interactions with client
io.sockets.on('connection', function(socket){
//send data to client
setInterval(function(){
socket.emit('date', {'date': new Date()});
}, 1000);
//recieve client data
socket.on('client_data', function(data){
var spawn = require('child_process').spawn;
console.log('pre-spawned');
spawn(data.cmd, data.args, {});
setTimeout(function() {
console.log('hello world!');
}, 1000);
var aptIO = require('socket.io-client');
var router = require('socket.io-events')();
var socket2 = aptIO.connect('localhost:8002', {reconnect: true});
router.on('connection', function(s){
//send data to client
console.log('apt');
router.on('*', function(sock, args, next){
var name = args.shift(), msg = args.shift();
console.log(name + " " + JSON.stringify(msg));
sock.emit(bytes);
io.sockets.emit('msg', {'msg': JSON.stringify(msg)})
next();
});
s.emit(bytes);
});
console.log('spawned');
// getting runtime exceptions here...have tried various things...
socket2.use(router);
});
});
With the help from JGreenwell, I was able to resolve me issue.
I ended up having the node server communicate to the client html page via socket.io connection for messages. The node server would launch the cmd line executable providing it the port to connect to which is different from the socket.io port used.
Once started, the executable would communicate with the server via the net module. The server would just pass the information on to the socket.io connection. the js in the html page knows how to parse the message in order to increment the progress bar and list the messages in a text area control.
I took it even further by having the messages be broadcast-ed to multiple clients on the socket.io connection.

pass port number to page loaded in node.js/socket.io

Okay, I have a simple test server set up using socket.io in node.js. My goal is to run the same server on a few different ports to test some load balanced conditions and synchronization tests.
Here is what the server looks like:
var app = require('http').createServer(handler),
io = require('socket.io').listen(app),
fs = require('fs'),
port = process.argv[1]; // listen on port number passed via command line
app.listen(port);
function handler (req, res) {
console.log('request', {remotePort: req.connection.remotePort, remoteAddress: req.connection.remoteAddress, url: req.url});
// how do I pass the port number here?
fs.readFile(__dirname + '/chat.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading chat.html');
}
res.writeHead(200);
res.end(data);
});
}
io.sockets.on('connection', function (socket) {
// do chatty stuff
});
The question is: what is the easiest way to get the port number into chat.html (see comment in code above)? Is there a way to do this with node or fs? Do I need to Express set up with templates?
Wonder what node will let me do with the query string; could I just stick the port in there and pick it out with jQuery once the page loads?
Thanks, in advance!
html is for static contents. so you can not use for dynamic contents.
so easiest way is using templates like ejs, jade and jquery template.
but you don't want you can change contents from chat.html
function(err, data) {
data = data.replace() // like this
}
I'm not recommend this way.
This is an old question, but decided to answer it with a more suiting answer still.
Because you're listening on the same port on both the http and socket.io, you can just change the script on the client to connect to the same address as the webpage was loaded, like so:
var socket = io.connect(window.location.href);
If the server was just a normal websocket server, you could do instead this:
var socket = new WebSocket(window.location.href.replace('http', 'ws'));

Resources