LEARNING JAVASCRIPT - Trang 313

Filesystem Access

Many introductory programming books cover filesystem access because it’s considered

a critical part of “normal” programming. Poor JavaScript: up until Node, it wasn’t in

the filesystem club.
The examples in this chapter assume your project root is /home/<jdoe>/fs, which is a

typical path on a Unix system (replace <jdoe> with your username). The same princi‐

ples apply on a Windows system (where your project root might be C:\Users\<John

Doe>\Documents\fs).
To create a file, use

fs.writeFile

. Create a file in your project root called write.js:

const

fs

=

require

(

'fs'

);

fs

.

writeFile

(

'hello.txt'

,

'hello from Node!'

,

function

(

err

) {

if

(

err

)

return

console

.

log

(

'Error writing to file.'

);

});

This will create a file in the directory you’re in when you run write.js (assuming you

have sufficient privileges in that directory, and there isn’t a directory or read-only file

called hello.txt already). Whenever you invoke a Node application, it inherits its cur‐

rent working directory from where you run it from (which may be different than

where the file lives). For example:

$ cd /home/jdoe/fs
$ node write.js # current working dir is /home/jdoe/fs
# creates /home/jdoe/fs/hello.txt

$ cd .. # current working dir is now /home/jdoe
$ node fs/write.js # creates /home/jdoe/hello.txt

Node provides a special variable,

__dirname

, which is always set to the directory in

which the source file resides. For example, we can change our example to:

const

fs

=

require

(

'fs'

);

fs

.

writeFile

(

__dirname

+

'/hello.txt'

,

'hello from Node!'

,

function

(

err

) {

if

(

err

)

return

console

.

error

(

'Error writing to file.'

);

});

Now write.js will always create hello.txt in /home/<jdoe>/fs (where write.js is located).

Using string concatenation to join

__dirname

and our filename isn’t very platform-

agnostic; this could cause problems on a Windows machine, for example. Node pro‐

vides platform-independent pathname utilities in the module

path

, so we can rewrite

this module to be more friendly on all platforms:

const

fs

=

require

(

'fs'

);

const

path

=

require

(

'path'

);

Filesystem Access | 289

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.