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
Related
I have read that Javascript can be used for back-end of a website, so like server side scripting. I have seen here that nodejs is accepted by Google cloud storage but using node js which confuses me as I don't know how to use it with a website in a text editor e.g. Brackets.
I have been trying to create a server and use the console to show that someone has connected:
var http = require("http");
var fs = require("fs");
var lemon = 2;
function send404Response(response) {
response.writeHead(404, {"Content-Type": "text/plain"});
response.write("Error 404");
response.end;
}
function onRequest(request, response) {
if (request.method == 'GET' && request.url == '/'){
response.writeHead(200, {"Content-Type": "text/html"});
//sends back a readable stream
fs.createReadStream("./index.html").pipe(response);
} else {
send404Response(response);
}
}
http.createServer(onRequest).listen(8080);
console.log("Server is now running...");
'require' was used before it was defined. var http = require("http"); is the first error and I don't know what to do nor can I find any help except that I'm not supposed to do require for a website.
In review please answer these questions:
how do you use Javascript for server side scripting and some
tutorials would be useful.
how to use nodejs with a website, since its a command line.
what is the issue with the code?
Also which port am I supposed to use when using brackets live update?
Please if there is an issue with the question please leave a comment I have tried to follow the rules.
I'm learning Node.js I have created server and client .js files but I don't understand few things. For example, in the webserver.js file, I don't know what is the use of pathname. Similarly, in the client.js file, what are dataand path?
If you think I should read about the basics of it, please provide me a useful link if you can. I tried to find but didn't work.
webserver.js
var fs=require('fs');
var url=require('url');
var http=require('http');
http.createServer(function(request, response){
var pathname=url.parse(request.url).pathname;
console.log("Pathname: "+pathname+"Request.url: "+request.url);
fs.readFile(pathname.substr(1), function(err, data){
if(err){
console.log("Error reading.");
response.writeHead(400, {'content-type' : 'text/html'});
}else{
response.writeHead(200, {'content-type' : 'text/html'});
response.write(data.toString());
}
response.end();
});
}).listen(8081);
console.log("Server is running.");
client.js
var http=require('http');
var options={
host: 'localhost',
port: '8081',
path: '/index.html'
};
var callback=function(response){
var body='';
response.on('data', function(data){
body+=data;
});
response.on('end', function(){
console.log("Data received.");
});
}
var req=http.request(options, callback);
req.end();
The original code souce is here: Code
pathname is the path section of the URL, that comes after the host and before the query, including the initial slash if present.
pathname is the path requested to the http server. The example pathname for this question is /questions/40276802/what-is-client-path-and-data-in-this-code. The path in client.js is the same deal.
You can find documentation on parsing the URL into the pathname from the Node.js docs: https://nodejs.org/api/http.html#http_message_url
Node's HTTP client uses streams, which emit several events. data is called with a buffer, which you usually will add to an array then concat later (as the code does). end is called when all buffers are sent.
You can find documentation on handling events from streams from the Node.js docs: https://nodejs.org/api/stream.html#stream_class_stream_readable
pathname is the requested path. You should check the documentation for the url package: npm-url
In your client.js: data is the response data from the server. Again check http documentation: HTTP|Node.js
For learning callbacks and all about Node.js: nodeschool.io
var http = require("http");
var fs = require("fs");
http.createServer(function(request, response) {
console.log("User request received");
response.writeHead(200, {"Content-Type": "Text/plain"});
fs.createReadStream(process.argv[3]).pipe(response);
response.end();
}).listen(process.argv[2]);
console.log("Server is running...");
This program takes the port number and the file path as command line parameters.
When I run it in node, even though I pass the correct command line arguments, the file is not served when accessed from the browser
I don't know where the error is occurring
This might not be the best answer but it looks like the call to response.end() is closing the stream before the file is served. Following the logic on this answer:
createReadStream().pipe() Callback
You need a callback on when the stream closes, so I found this works but again, I don't know if this is the most elegant solution:
var http = require("http");
var fs = require("fs");
http.createServer(function(request, response) {
console.log("User request received");
response.writeHead(200, {"Content-Type": "Text/plain"});
var t = fs.createReadStream(process.argv[3]).pipe(response);
t.on('close', function(){
response.end();
});
}).listen(process.argv[2]);
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?
I'm following this beginner node.js tutorial (http://debuggable.com/posts/understanding-node-js:4bd98440-45e4-4a9a-8ef7-0f7ecbdd56cb) and i have just created my first server using this code:
var http = require("http")
http.createServer(
function(request, response){
response.writeHead(200, {"Content-Type":"text/plain"})
response.write("hello world")
response.end
}
).listen(3333)
This works great, but when i go to the url localhost:3333/ i see the words "hello world" very briefly and then it just dissapears.
See this vine for a quick video: https://vine.co/v/MBJrpBEQvLX
Any ideas?
Put your Hello World in the response#end(). I'd also suggest that your read the NodeJS API
http.createServer(function (req, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Hello World\n');
}).listen(3333);
You forgot to put parentheses at the end of response.end().
The code should read:
var http = require("http");
http.createServer( function(request, response){
response.writeHead(200, {"Content-Type":"text/plain"});
response.write("hello world");
response.end();
}).listen(3333);