let
counts
=
filenames
.
map
(
f
=>
{
try
{
const
data
=
fs
.
readFileSync
(
f
, {
encoding
:
'utf8'
});
return
`
${
f
}
:
${
data
.
split
(
'\n'
).
length
}
`
;
}
catch
(
err
) {
return
`
${
f
}
: couldn't read file`
;
}
});
console
.
log
(
counts
.
join
(
'\n'
));
process
also gives you access to environment variables through the object
pro
cess.env
. Environment variables are named system variables that are primarily used
for command-line programs. On most Unix systems, you can set an environment
variable simply by typing
export VAR_NAME=some value
(environment variables are
traditionally all caps). On Windows, you use
set VAR_NAME=some value
. Environ‐
ment variables are often used to configure the behavior of some aspect of your pro‐
gram (without your having to provide the values on the command line every time
you execute the program).
For example, we might want to use an environment variable to control whether or
not our program logs debugging information or “runs silently.” We’ll control our
debug behavior with an environment variable
DEBUG
, which we’ll set to
1
if we want to
debug (any other value will turn debugging off):
const
debug
=
process
.
env
.
DEBUG
===
"1"
?
console
.
log
:
function
() {};
debug
(
"Visible only if environment variable DEBUG is set!"
);
In this example, we create a function,
debug
, that is simply an alias for
console.log
if
the environment variable
DEBUG
is set, and a null function—a function that does noth‐
ing—otherwise (if we left
debug
undefined, we would generate errors when we tried
to use it!).
In the previous section, we talked about the current working directory, which defaults
to the directory you execute the program from (not the directory where the program
exists).
process.cwd
tells you what the current working directory is, and
pro
cess.chdir
allows you to change it. For example, if you wanted to print out the
directory in which the program was started, then switch the current working direc‐
tory to the directory where the program itself is located, you could do this:
console.log(
`Current directory:
${
process
.
cwd
()
}
`
);
process
.
chdir
(
__dirname
);
console.log(
`New current directory:
${
process
.
cwd
()
}
`
);
Process | 293