LEARNING JAVASCRIPT - Trang 321

Note that in this example, we don’t have to specify encoding:

rs

is simply piping bytes

from stream.txt to

ws

(which is writing them to stream_copy.txt); encoding only mat‐

ters if we’re trying to interpret the data.
Piping is a common technique for moving data. For example, you could pipe the con‐

tents of a file to a webserver’s response. Or you could pipe compressed data into a

decompression engine, which would in turn pipe data out to a file writer.

Web Servers

While Node is being used in many applications now, its original purpose was to pro‐

vide a web server, so we would be remiss not to cover this usage.
Those of you who have configured Apache—or IIS, or any other web server—may be

startled at how easy it is to create a functioning web server. The

http

module (and its

secure counterpart, the

https

module) exposes a

createServer

method that creates a

basic web server. All you have to do is provide a callback function that will handle

incoming requests. To start the server, you simply call its

listen

method and give it a

port:

const

http

=

require

(

'http'

);

const

server

=

http

.

createServer

(

function

(

req

,

res

) {

console.log(

`

${

req

.

method

}

${

req

.

url

}

`

);

res

.

end

(

'Hello world!'

);

});

const

port

=

8080

;

server

.

listen

(

port

,

function

() {

// you can pass a callback to listen that lets you know

// the server has started

console.log(

`server startd on port

${

port

}

`

);

});

Most operating systems prevent you from listening on the default

HTTP port (80) without elevated privileges, for security reasons.

As a matter of fact, you need elevated privileges to listen on any

port below 1024. Of course this is easy to do: if you have sudo

access, you can just run your server with sudo to gain elevated

privileges, and listen on port 80 (as long as nothing else is). For

development and testing purposes, it’s common to listen on ports

above 1024. Numbers like 3000, 8000, 3030, and 8080 are com‐

monly picked because they are memorable.

If you run this program and visit

http://localhost:8080

in a browser, you will see

Hello

world!

. On the console, we’re logging all requests, which consist of a method (some‐

Web Servers | 297

Liên Kết Chia Sẽ

** Đây là liên kết chia sẻ bới cộng đồng người dùng, chúng tôi không chịu trách nhiệm gì về nội dung của các thông tin này. Nếu có liên kết nào không phù hợp xin hãy báo cho admin.