Instructor: The simplest way to get data from a Node script is to invoke Node using the P option. P stands for print. Here, we pass the string. Let's see how many CPUs this system has.
Note that we don't have to require a core Node.js module like OS when it's invoked like this. We can store the result in a Bash variable easily as well, and then we'll echo CPUs.
How do we send the command link parameters into a Node.js script? For example, let's say we want a script that can parse and check the value of a query string. Let's write a quick Node script with an API that looks like this.
I'll call it QueryStringCheck, and then we'll pass a query string like this. Then, we'll tell it what property in here we want to check and then the expected value of it. Let's go ahead and implement that.
I have my QS check file here. Note that I've already given it execute permissions. You have to do that in order to invoke it directly. First of all, I add a Node shebang at the top. This tells the shell to use the Node.js binary to invoke this script.
Let's get the parameters passed to the script. All of the script's parameters are stored in the process that inaudible . What we're going to do is we're going to slice off the first two elements of it.
The first element is always the path to the Node binary, and the second element is the file path to this script. We don't need those, so I sliced them off. Then in here is where we're going to have the parameters that we're interested in. I have the query string that the user passed, their query string property that they want checked, and then the expected value for that property.
First off, down here we'll do a little bit of input validation. We'll say that all of these parameters have to be defined. If they are empty, we'll throw an error. First, we'll write to standard error, and then we'll exit with a 1 status.
Let's get the actually value. For that, I'll need the parse meth in from the query string module. I'll run parse on the query string, and then we'll grab the prop that the user passed. Then, let's do the actual comparison. We'll say if actual there is equal to the expected.
We'll write that out and we'll exit with a 0status. If they're not equal, we'll write to standard error and say they're not equal and exit with a 1 or error status. Let's run this and try it out. Invoke our scripts. Let's check the exit code. It's a 0Let's change this so it's not true and check the exit status. It's a 1. Cool, looks like it's working.