1. Trang chủ >
  2. Công Nghệ Thông Tin >
  3. Kỹ thuật lập trình >

Section 19.7: Setting alias for node version

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (2.79 MB, 334 trang )


Chapter 20: http

Section 20.1: http server

A basic example of HTTP server.

write following code in http_server.js file:

var http = require('http');

var httpPort = 80;

http.createServer(handler).listen(httpPort, start_callback);

function handler(req, res) {

var clientIP = req.connection.remoteAddress;

var connectUsing = req.connection.encrypted ? 'SSL' : 'HTTP';

console.log('Request received: '+ connectUsing + ' ' + req.method + ' ' + req.url);

console.log('Client IP: ' + clientIP);

res.writeHead(200, "OK", {'Content-Type': 'text/plain'});

res.write("OK");

res.end();

return;

}

function start_callback(){

console.log('Start HTTP on port ' + httpPort)

}



then from your http_server.js location run this command:

node http_server.js



you should see this result:

> Start HTTP on port 80



now you need to test your server, you need to open your internet browser and navigate to this url:

http://127.0.0.1:80



if your machine running Linux server you can test it like this:

curl 127.0.0.1:80



you should see following result:

ok



in your console, that running the app, you will see this results:

> Request received: HTTP GET /

> Client IP: ::ffff:127.0.0.1



GoalKicker.com – Node.js Notes for Professionals



93



Section 20.2: http client

a basic example for http client:

write the follwing code in http_client.js file:

var http = require('http');

var options = {

hostname: '127.0.0.1',

port: 80,

path: '/',

method: 'GET'

};

var req = http.request(options, function(res) {

console.log('STATUS: ' + res.statusCode);

console.log('HEADERS: ' + JSON.stringify(res.headers));

res.setEncoding('utf8');

res.on('data', function (chunk) {

console.log('Response: ' + chunk);

});

res.on('end', function (chunk) {

console.log('Response ENDED');

});

});

req.on('error', function(e) {

console.log('problem with request: ' + e.message);

});



req.end();



then from your http_client.js location run this command:

node http_client.js



you should see this result:

> STATUS: 200

> HEADERS: {"content-type":"text/plain","date":"Thu, 21 Jul 2016 11:27:17

GMT","connection":"close","transfer-encoding":"chunked"}

> Response: OK

> Response ENDED



note: this example depend on http server example.



GoalKicker.com – Node.js Notes for Professionals



94



Chapter 21: Using Streams

Parameter

Definition

Readable Stream type of stream where data can be read from

Writable Stream



type of stream where data can be written to



Duplex Stream



type of stream that is both readable and writeable



Transform Stream type of duplex stream that can transform data as it is being read and then written



Section 21.1: Read Data from TextFile with Streams

I/O in node is asynchronous, so interacting with the disk and network involves passing callbacks to functions. You

might be tempted to write code that serves up a file from disk like this:

var http = require('http');

var fs = require('fs');

var server = http.createServer(function (req, res) {

fs.readFile(__dirname + '/data.txt', function (err, data) {

res.end(data);

});

});

server.listen(8000);



This code works but it's bulky and buffers up the entire data.txt file into memory for every request before writing

the result back to clients. If data.txt is very large, your program could start eating a lot of memory as it serves lots of

users concurrently, particularly for users on slow connections.

The user experience is poor too because users will need to wait for the whole file to be buffered into memory on

your server before they can start receiving any contents.

Luckily both of the (req, res) arguments are streams, which means we can write this in a much better way using

fs.createReadStream() instead of fs.readFile():

var http = require('http');

var fs = require('fs');

var server = http.createServer(function (req, res) {

var stream = fs.createReadStream(__dirname + '/data.txt');

stream.pipe(res);

});

server.listen(8000);



Here .pipe() takes care of listening for 'data' and 'end' events from the fs.createReadStream(). This code is not only

cleaner, but now the data.txt file will be written to clients one chunk at a time immediately as they are received

from the disk.



Section 21.2: Piping streams

Readable streams can be "piped," or connected, to writable streams. This makes data flow from the source stream

to the destination stream without much effort.

var fs = require('fs')

var readable = fs.createReadStream('file1.txt')



GoalKicker.com – Node.js Notes for Professionals



95



var writable = fs.createWriteStream('file2.txt')

readable.pipe(writable) // returns writable



When writable streams are also readable streams, i.e. when they're duplex streams, you can continue piping it to

other writable streams.

var zlib = require('zlib')

fs.createReadStream('style.css')

.pipe(zlib.createGzip()) // The returned object, zlib.Gzip, is a duplex stream.

.pipe(fs.createWriteStream('style.css.gz')



Readable streams can also be piped into multiple streams.

var readable = fs.createReadStream('source.css')

readable.pipe(zlib.createGzip()).pipe(fs.createWriteStream('output.css.gz'))

readable.pipe(fs.createWriteStream('output.css')



Note that you must pipe to the output streams synchronously (at the same time) before any data 'flows'. Failure to

do so might lead to incomplete data being streamed.

Also note that stream objects can emit error events; be sure to responsibly handle these events on every stream, as

needed:

var readable = fs.createReadStream('file3.txt')

var writable = fs.createWriteStream('file4.txt')

readable.pipe(writable)

readable.on('error', console.error)

writable.on('error', console.error)



Section 21.3: Creating your own readable/writable stream

We will see stream objects being returned by modules like fs etc but what if we want to create our own streamable

object.

To create Stream object we need to use the stream module provided by NodeJs

var fs = require("fs");

var stream = require("stream").Writable;

/*

* Implementing the write function in writable stream class.

* This is the function which will be used when other stream is piped into this

* writable stream.

*/

stream.prototype._write = function(chunk, data){

console.log(data);

}

var customStream = new stream();

fs.createReadStream("am1.js").pipe(customStream);



This will give us our own custom writable stream. we can implement anything within the _write function. Above

method works in NodeJs 4.x.x version but in NodeJs 6.x ES6 introduced classes therefore syntax have changed.

Below is the code for 6.x version of NodeJs

GoalKicker.com – Node.js Notes for Professionals



96



Xem Thêm
Tải bản đầy đủ (.pdf) (334 trang)

Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×