How to run a project on node.js - javascript

I am a beginner to node.js and i did a sample code it shown below,
var http = require("http");
var server = http.createServer(function(request,response) {
response.writeHead(200, {
"content-Type" : "text/html"
});
response.end("Hello again");
}).listen(8888);
and when i run this file on eclise Run as ------> Node project
and when i open the browser with url localhost:8888 it shows web page not availble. can u guys help me to find out. I already installed node.js on my system and npm alse. am i missing something?

There is no request or response object in the scope of your request callback. You need to define them as arguments of the callback function.
var http = require("http");
var server = http.createServer(function(request, response) {
response.writeHead(200, {
"content-Type" : "text/html"
});
response.end("Hello again");
}).listen(8888);
You should definitely get an error though - are you sure your IDE is set up properly?

You never accept the "request" variable. Below is a working version of what you're attempting.
var http = require("http");
var server = http.createServer();
server.on('request', function(request, response) {
response.writeHead(200, {
"content-Type" : "text/html"
});
response.end("Hello again");
});
server.listen(8888);

Can you please tell me where you found response object? http.createServer return a callback function which have two arguments. They are response and request. response use for send data/information to client and request use for get data/information from client. So in your http.createServer callback function add response and request arguments. After that in callback function use response object. Like this.
var http = require("http");
var server = http.createServer(function(request, response) {
response.writeHead(200, {
"content-Type" : "text/html"
});
response.end("Hello again");
}).listen(8888);

Related

How can i make a local server using nodeJs?

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

What is client, path and data in this code?

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

I want to start a simple http web server but this isn't working

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]);

node.js send data to client?

I wonder how can I send data from node.js to client?
example node.js code -
var http = require('http');
var data = "data to send to client";
var server = http.createServer(function (request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.end("Hello World\n");
}).listen(8125);
Now, I want to send the data variable to client and log it with JavaScript..
How can I do that?
Thanks ;)
EDIT: Does anyone know how to send array?
If You Want to do it after response.end you should use Socket.io or Server Send Events.
If you want it before res.end, you would make your code look like:
var http = require('http');
var data = "data to send to client";
var server = http.createServer(function (request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write(data); // You Can Call Response.write Infinite Times BEFORE response.end
response.end("Hello World\n");
}).listen(8125);

node.js write http response to stream

i'm fetching some binary data over http. My code looks like:
var writeStream = fs.createWriteStream(fileName);
request(url, function(err, res) {
res.socket.pipe(writeStream);
});
now the output file is created but the filesize is 0. The url is correct though, i verified that with wget.
Thanks in advance & best regards
The callback for http.request only supplies one argument, which is a reference to the response of the request. Try
http.request(url, function(res) {
res.pipe(writeStream);
});
Also note that the ClientResponse implements ReadableStream, so you should use .pipe rather than .socket.pipe.
I'm assuming that here request is from mikeal's request library rather than being an instance of http.request. In that case you can simply do request(url).pipe(writeStream);
Remember that for debugging purposes, you can always pipe to process.stdout.
var readStream = fs.createReadStream(fileName);
request(url, function(err, res) {
readStream.pipe(res);
readStream.on('end', function() {
//res.end({"status":"Completed"});
});
});

Categories