LEARNING JAVASCRIPT - Trang 316

2

The name

argv

is a nod to the C language. The v is for vector, which is similar to an array.

const

fs

=

require

(

'fs'

);

fs

.

readdir

(

'data'

,

function

(

err

,

files

) {

if

(

err

) {

console

.

error

(

"Fatal error: couldn't read data directory."

);

process

.

exit

(

1

);

}

const

txtFiles

=

files

.

filter

(

f

=>

/\.txt$/i

.

test

(

f

));

if

(

txtFiles

.

length

===

0

) {

console

.

log

(

"No .txt files to process."

);

process

.

exit

(

0

);

}

// process .txt files...

});

The

process

object also gives you access to an array containing the command-line

arguments passed to the program. When you execute a Node application, you can

provide optional command-line arguments. For example, we could write a program

that takes multiple filenames as command-line arguments, and print out the number

of lines of text in each file. We might invoke the program like this:

$ node linecount.js file1.txt file2.txt file3.txt

The command-line arguments are contained in the

process.argv

array.

2

Before we

count the lines in our files, let’s print out

process.argv

so we know what we’re get‐

ting:

console

.

log

(

process

.

argv

);

Along with file1.txt, file2.txt, and file3.txt, you’ll see a couple of extra elements at the

beginning of the array:

[

'node'

,

'/home/jdoe/linecount.js'

,

'file1.txt'

,

'file2.txt'

,

'file3.txt'

]

The first element is the interpreter, or program that interpreted the source file (

node

,

in our case). The second element is the full path to the script being executed, and the

rest of the elements are any arguments passed to the program. Because we don’t need

this extra information, we’ll just use

Array.slice

to get rid of it before counting the

lines in our files:

const

fs

=

require

(

'fs'

);

const

filenames

=

process

.

argv

.

slice

(

2

);

292 | 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.