Operating System
The
os
module provides some platform-specific information about the computer on
which the app is running. Here is an example that shows the most useful information
that
os
exposes (and their values on my cloud-based dev machine):
const
os
=
require
(
'os'
);
console
.
log
(
"Hostname: "
+
os
.
hostname
());
// prometheus
console
.
log
(
"OS type: "
+
os
.
type
());
// Linux
console
.
log
(
"OS platform: "
+
os
.
platform
());
// linux
console
.
log
(
"OS release: "
+
os
.
release
());
// 3.13.0-52-generic
console
.
log
(
"OS uptime: "
+
(
os
.
uptime
()
/
60
/
60
/
24
).
toFixed
(
1
)
+
" days"
);
// 80.3 days
console
.
log
(
"CPU architecture: "
+
os
.
arch
());
// x64
console
.
log
(
"Number of CPUs: "
+
os
.
cpus
().
length
);
// 1
console
.
log
(
"Total memory: "
+
(
os
.
totalmem
()
/
1e6
).
toFixed
(
1
)
+
" MB"
);
// 1042.3 MB
console
.
log
(
"Free memory: "
+
(
os
.
freemem
()
/
1e6
).
toFixed
(
1
)
+
" MB"
);
// 195.8 MB
Child Processes
The
child_process
module allows your app to run other programs, whether it be
another Node program, an executable, or a script in another language. It’s beyond the
scope of this book to cover all of the details of managing child processes, but we will
consider a simple example.
The
child_process
module exposes three primary functions:
exec
,
execFile
, and
fork
. As with
fs
, there are synchronous versions of these functions (
execSync
,
execFileSync
, and
forkSync
).
exec
and
execFile
can run any executable supported
by your operating system.
exec
invokes a shell (which is what underlies your operat‐
ing system’s command line; if you can run it from the command line, you can run it
from
exec
).
execFile
allows you to execute an executable directly, which offers
slightly improved memory and resource use, but generally requires greater care.
Lastly,
fork
allows you to execute other Node scripts (which can also be done with
exec
).
fork
does invoke a separate Node engine, so you’re paying the
same resource cost you would with exec; however, fork gives you
access to some interprocess communication options. See the
for more information.
Because
exec
is the most general, and the most forgiving, we’ll use it in this chapter.
294 | Chapter 20: Node