Launching Node.js Scripts
Node is an interpreted language and environment, not a compiled one. There are three main way to launch Node code:
- REPL (already covered in the previous lesson)
- Eval option
- Launching Node code from a file
Eval Option
If all we need is a quick set of statements, there’s a eval -e option that allows us to run inline JavaScript/Node.js. For example, to print the current date, run this in your Terminal / Command Prompt:
node -e "console.log(new Date())"
Another example prints Node version:
node -e "console.log(process.versions.node)"
Node eval (-e flag) is useful in npm and bash scripts because it allows you to execute Node in a very compact manner in the bash, zsh or any other shell environment without having to have a Node file. You can get versions, OS information or run any Node code such as working with a file system, database or HTTP.
Launching Node Code from a File
This is the most common use case because it allows you to save long Node programs and run them. To run a Node.js script from a file, simply type node filename.
For example, to launch code from a program.js file which is located in a current folder, simply execute
node program.js
The file must be in the same folder. If you need to execute code from a file which is in a different folder, just provide the relative or absolute path:
node ./app/server.js
node /var/www/app/server.js
The .js is optional as long as you have a file with such extension. In other words, if you have server.js you can execute node server.
If you have index.js in a folder, you can simply execute with a dot/period/full stop which in POSIX means the current folder or with a path to that folder.
For example:
node .
node /var/www/app
Are equivalent to
node index.js
node index
and
node /var/www/app/index.js
node /var/www/app/index
Node.js Globals
Despite being modeled after one standard, Node.js and browser JavaScript differ when it comes to globals. As you might know, in browser JavaScript we have a window object. However, in Node.js, it is absent (obviously we don’t deal with a browser window), but developers are provided with new objects/keywords:
- process
- global
- module.exports and exports
So, let’s take a look at the main differences between Node.js and JavaScript.
global
There is a variable named global which is accessible by any Node script or program. It refers to the global object. This object has properties. For example global.process or global.require or global.console.
Any first level property of the global object is accessible without the global prefix. For example, global.process and just process will be the same.
The GLOBAL alias for global can be seen in older project but is deprecated. Use global instead of GLOBAL.
Main Globals
These are the main properties of the global object and are known as globals:
- process
- require()
- module and module.exports
- console and console.log()`
- setTimeout() and setInterval()
- __dirname and __filename
console.log() and setTimeout() work similarly to the browser methods. We will cover process, require() and module.exports in the following lessons.
__dirname, __filename and process.cwd
__dirname is an absolute path to the file in which the global variable is called, whereas process.cwd is an absolute path to the process that runs the script. The latter might not be the same as the former if we started the program from a different folder, such as node ./code/program.js.
__filename is similar to __dirname but only with the file name attached to the absolute path of the currently running file/script.
Node.js Process
Each Node.js script that runs is, in essence, a process. For example,
ps aux | grep 'node'
outputs all Node.js programs running on a machine. Conveniently, developers can access useful process information in code with the process
object, e.g., node -e "console.log(process.pid)"
will print the process ID.
Other useful
process
information includes:env
: Environment variablesargv
: Command-line argumentsexit()
: Method to exit/terminate process
Let's see how to use each of them.
Environment Variables
Environment variables can be accessed via the
env
attribute:console.log(process.env)
{ SHELL: '/bin/bash',
USER: 'jordan',
HOME: '/home/jordan',
...
}
A short one-liner can set the environment variable in bash, and then run Node eval to print the value. This is a bash/Terminal/ Command Prompt command which will print “development”:
NODE_ENV=development node -e "console.log(process.env.NODE_ENV)"
NODE_ENV is a convention. Common values include:
- development: used by developers to code verbose error messages and logs for debugging
- production: used by developers to hides excessive error messages and logs
This is just a convention but some libraries and frameworks will augment their behavior to hide error messages, e.g., Express.
Command-Line Arguments
To access CLI arguments, use the
process.argv
property which is an array.
For example, if the command is
node app.js arg1 arg2 arg3=val3
The first two elements are ‘node’ and the application's name while the rest are the command-line arguments. Thus,
process.argv
:[
'node',
'app.js',
'arg1',
'arg2',
'arg3=val3'
]
Exiting a Process
To exit a process, use the
exit
function:process.exit()
When your application encounters an error, you want to exit with errors. Exit codes can also be specified
// this process failed
process.exit(1)
// this process failed with a different code
process.exit(129)
// this process exits successfully
process.exit(0)
Different failure codes can be used to differentiate types of failure. And knowing how an application failed allows the developers the means to program an appropriate response.
1. Microsoft: DEV283x: Introduction to NodeJS
No comments:
Post a Comment