I have the following Node.js code:
var http = require('http');
http.createServer(function(req, res)) {
console.log("URL request"+req.url);
res.writeHead(200, {'Content-Type':'text/plain'});
res.end('Hello World\n');
}).listen(9898, '127.0.0.1');
console.log('Server locally running at http://127.0.0.1:9898/');
I am using the Socket class in Java to make a socket that also connects to port 9898. I want whatever the Node.js writes (in this case 'Hello World'), to be processed by a Java class. So far, this is what I have for the Java class:
Socket s = new Socket(serverAddress, 9898);
BufferedReader input =
new BufferedReader(new InputStreamReader(s.getInputStream()));
My question is how do I get the 'Hello World' to be read by the Java code, so that whenever I call System.out.println(input.readLine()), it prints 'Hello World'?
you had an extra ')' on the third line, but your code seems to otherwise work:
var http = require('http');
http.createServer(function(req, res) {
console.log("URL request"+req.url);
res.writeHead(200, {'Content-Type':'text/plain'});
res.end('Hello World\n');
}).listen(9898, '127.0.0.1');
console.log('Server locally running at http://127.0.0.1:9898/');
i guess you need to create some java functionality to make a http request to the url:port the node server is running on. it probably wont be as simple as 'input.readLine()'.
maybe something like this will help for getting the java code to get the data from node:
How can I get an http response body as a string in Java?
Related
I am trying to build a Puppeteer app that can be uploaded to a web server and receive parameters via the URL, but I can't seem find a way to get the current URL from my browser using Node. Right now I have a default server.js file created by Visual Studio which I modified to include code for getting the URL, but when I run the file I get an object promise error for window.location.href.
Here is the codeL
'use strict';
var http = require('http');
var port = process.env.PORT || 1337;
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
var url = window.location.href;
res.end('Hello World\n' + url);
}).listen(port);
My goal is to be able to get the URL and then pass it to my Puppeteer script as a parameter when it is run. The above code should result in a url value of http://localhost:1337 which could then be modified to include any additional parameters by appending query strings.
Next I tried getting the URL outside of the createServer loop by appending the following:
var url = window.location.href;
document.write(url);
That causes the app to crash with no error message beyond failing to connect to the server.
This is my first Node.js application, so the concept of server side javascript is new to me.
I'm trying to make a local server using nodeJs but its not working.
What is tried
var http = require('http');
http.createServer(function(req, res) {
res.write('Hello');
req.end();
}).listen(8080);
Be careful when using response.end!
What is the difference between response.end() and response.send()?
response.end() will always send an HTML string, while response.send() can send any object type. For your example, both will serve the purpose since you are sending an HTML string of 'hello', but keep these cautions in mind as you proceed to build your server!
var http = require('http');
//Example with response.end()
http.createServer(function(request, response) {
response.end('Hello');
}).listen(8080);
//Example with response.send()
http.createServer(function(request, response) {
response.send('Hello');
}).listen(8080);
//Example with res.send() object
http.createServer(function(request, response) {
response.send({ message: 'Hello', from: 'Happy Dev' });
}).listen(8080);
The res (which stand for response) in the callback is a Stream. After you write all you want (headers, body) to the stream, you must end it like so:
res.end();
What you have is req.end().
Using req instead of res was your error.
Also, since you only write one line in this contrived example, you could write the buffer and end the stream in one go:
const server = http.createServer(function (req, res) {
res.end('Hello');
});
server.listen(8080);
Docs for response.end
I'm trying to display a php page using javascript with express functions. An example code:
var express = require('express')
var app = express()
app.get('/', function (req, res) {
res.send('Hello World!')
})
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)
})
I have a php page with html and javascript functions that displays different data from database and I'm not sure how to call the page from the javascript file. I tried putting it in script tags on the php page but how do I then execute the output of the php page in the res.send();
You're getting things wrong. You can't load your express code into your PHP or vice versa (in fact you can, but it would be too much work).
To make your PHP code talk to your express/node code, you should create an interface between them. I think a RESTful interface would be the easiest one to build. The code you've provided is already a RESTful interface.
Then, in your PHP code (alongside with HTML and client-side JavaScript), you can
make an XHR or Ajax request to the express/node route (but you'll need to send a json, which is not so different from what you got: res.json({hello: 'Hello World'}). More about Express json response here).
Or, you do use a JSON request from PHP, which you can find more information here.
EDIT:
Ok, here is some PHP code:
<?php
$url = "localhost:3000/"; // this should the route you've defined on
// express. the `app.get('/')` part.
$json = file_get_contents($url);
var_dump(json_decode($json));
?>
And your express code should be like:
app.get('/', function(req, res){
res.json({hello: 'Hello World'})
})
Then, your PHP's var_dump should output:
{hello: 'Hello World'}
I just started last week learning JavaScript and Node.js. Before that I developed with Java WebObjects and VB.NET. I just want to learn it for my self.
My brain is hurting after this week because of closures and other JavaScript stuff.
And now the question. To create a simple Node server I always found some code like this.
var http = require("http");
http.createServer(function(request,response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}).listen(3000);
Is there any difference if I would write the code like this?
var http = require("http");
var serverCallback = function(request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.write("Hello World");
response.end();
}
var server = http.createServer(serverCallback);
server.listen(3000);
For me this is more readable. But I'm not really sure that its exact the same.
There is no difference in functionality. Use whatever style you like.
The only difference in this case how the variables are assigned, found this yesterday in HN
https://news.ycombinator.com/item?id=7672131
I'm having trouble wrapping my head around the pipe function shown in several Node.js examples for the net module.
var net = require('net');
var server = net.createServer(function (socket) {
socket.write('Echo server\r\n');
socket.pipe(socket);
});
Can anyone offer an explanation on how this works and why it's required?
The pipe() function reads data from a readable stream as it becomes available and writes it to a destination writable stream.
The example in the documentation is an echo server, which is a server that sends what it receives. The socket object implements both the readable and writable stream interface, so it is therefore writing any data it receives back to the socket.
This is the equivalent of using the pipe() method using event listeners:
var net = require('net');
net.createServer(function (socket) {
socket.write('Echo server\r\n');
socket.on('data', function(chunk) {
socket.write(chunk);
});
socket.on('end', socket.end);
});
pipe() reads from a readable stream and writes to a writeable stream, much like a Unix pipe. It does all "reasonable" things along the way with errors, end of files, if one side falls behind etc. Your particular example is slightly confusing because the socket is both readable and writeable.
An easier to understand example is in this SO question where you read from an http request and write to an http response.
There are 2 sockets per Server-Client Connection (2 endpoints). Socket binds IP Address:Port Number. The client gets assigned random port numbers, while the server has dedicated port number. This is the basic explanation of how socket works.
Piping is reserved for redirecting a readable stream to a writable stream.
What socket.pipe(socket) does?
It redirects all the data from the readable stream (server) to the writable stream (client). We can tweak this by adding event listeners as #hexacyanide has pointed out.
Consider the following request handler
var server = http.createServer(function(req, res){
console.log('Request for ' + req.url + ' by method ' + req.method);
if(req.method == 'GET'){
var fileurl;
if(req.url == '/')fileurl = '/index.html';
else {
fileurl = req.url;
}
}
var filePath = path.resolve('./public'+fileurl);
var fileExt = path.extname(filePath);
if(fileExt == '.html'){
fs.exists(filePath, function(exists){
if(!exists){
res.writeHead(404, {'Content-Type': 'text/html'});
res.end('<h1>Error 404' + filePath + 'not found </h1>');
//the end() method sends content of the response to the client
//and signals to the server that the response has been sent
//completely
return;
}
res.writeHead(200, {'Content-Type':'text/html'});
fs.createReadStream(filePath).pipe(res);
})
}
}
The fs.createReadStream method reads the file in the given file path (public/index.html) and pipe() writes it to the response (res) for client's view.