LEARNING JAVASCRIPT - Trang 306

and filesystem support, are not available in the browser for security reasons (can you

imagine the damage hackers could do if they could delete your files from the

browser?). Others, such as the ability to create a web server, simply aren’t very useful

in a browser.
It’s important to understand what’s JavaScript, and what’s part of an API. A program‐

mer who has always written browser-based code might reasonably assume that

window

and

document

are simply part of JavaScript. However, those are APIs provided

in the browser environment (which were covered in

Chapter 18

). In this chapter, we’ll

cover the APIs provided in Node.
If you haven’t already, make sure Node and npm are installed (see

Chapter 2

).

Modules

Modules are a mechanism for packaging and namespacing code. Namespacing is a

way to prevent name collisions. For example, if Amanda and Tyler both write a func‐

tion called

calculate

, and you simply cut and paste their functions into your pro‐

gram, the second one will replace the first. Namespacing allows you to somehow refer

to “Amanda’s

calculate

” and “Tyler’s

calculate

.” Let’s see how Node modules solve

this problem. Create a file called amanda.js:

function

calculate

(

a

,

x

,

n

) {

if

(

x

===

1

)

return

a

*

n

;

return

a

*

(

1

-

Math

.

pow

(

x

,

n

))

/

(

1

-

x

);

}

module

.

exports

=

calculate

;

And a file called tyler.js:

function

calculate

(

r

) {

return

4

/

3

*

Math

.

PI

*

Math

.

pow

(

r

,

3

);

}

module

.

exports

=

calculate

;

We could legitimately make the argument that Amanda and Tyler were both lazy in

naming their functions something so nondescript, but we’ll let it slide for the sake of

this example. The important line in both of these files is

modules.export = calcu

late

.

module

is a special object that Node makes available to implement modules.

Whatever you assign to its

exports

property will be what is exported from the mod‐

ule. Now that we’ve written a couple of modules, let’s see how we use them in a third

program. Create a file called app.js, and we’ll import these modules:

const

amanda_calculate

=

require

(

'./amanda.js'

);

const

tyler_calculate

=

require

(

'./tyler.js'

);

282 | Chapter 20: Node

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.