With the synchronous versions, error handling is accomplished with exceptions, so to
make our examples robust, we would wrap them in try/catch blocks. For example:
try
{
fs
.
writeFileSync
(
path
.
join
(
__dirname
,
'hello.txt'
),
'hello from Node!'
);
}
catch
(
err
) {
console
.
error
(
'Error writing file.'
);
}
The synchronous filesystem functions are temptingly easy to use.
However, if you are writing a webserver or networked application,
remember that Node’s performance derives from asynchronous
execution; you should always use the asynchronous versions in
those cases. If you are writing a command-line utility, it is usually
not an issue to use the synchronous versions.
You can list the files in a directory with
fs.readdir
. Create a file called ls.js:
const
fs
=
require
(
'fs'
);
fs
.
readdir
(
__dirname
,
function
(
err
,
files
) {
if
(
err
)
return
console
.
error
(
'Unable to read directory contents'
);
console.log(
`Contents of
${
__dirname
}
:`
);
console
.
log
(
files
.
map
(
f
=>
'\t'
+
f
).
join
(
'\n'
));
});
The
fs
module contains many more filesystem functions; you can delete files
(
fs.unlink
), move or rename files (
fs.rename
), get information about files and
directories (
fs.stat
), and much more. Consult the
for
more information.
Process
Every running Node program has access to a variable called
process
that allows it to
get information about—and control—its own execution. For example, if your appli‐
cation encounters an error so severe that it’s inadvisable or senseless to continue exe‐
cuting (often called a fatal error), you can immediately stop execution by calling
process.exit
. You can also provide a numeric exit code, which is used by scripts to
determine whether or not your program exited successfully. Conventionally, an exit
code of 0 has indicated “no error,” and a nonzero exit code indicates an error. Con‐
sider a script that processes .txt files in a subdirectory data: if there are no files to pro‐
cess, there’s nothing to do, so the program exits immediately, but it’s not an error. On
the other hand, if the subdirectory data doesn’t exist, we will consider this a more
serious problem, and the program should exit with an error. Here’s how that program
might look:
Process | 291