Previous Lecture Complete and continue  

  Process, CLI Arguments, Env Vars and Other Globals

So most of Node.js, it's JavaScript. We have arrays, strings, primitive, functions, objects, so all the syntax is the same. So that's a great thing. But Node.js, it's not 100%. It's not triple equals browser JavaScript.

So for example, how do you create a global variable? Because there is no window in Node.js. How do you work with modules? There is a global object, so you can spell it lowercase or uppercase and it has a lot of properties.

For example, __filename and __dirname. Those are properties to get. __filename will get you the path, the absolute path and then the file name, but the __dirname will get you only the path of the currently running script.

And then we have modules natively Node.js, so that's why there's global.module and global.require().

So, module, that's how you export, and require, that's how you import. Some of the other wonderful things that we now are able to use with Node.js, because in Browser JavaScript basically OS information, platform information, memory usage, all of those information is not accessible to you for the security reasons.

There is this magical properties called global.process. You can get your process ID, you can get version numbers, you can get the architecture, you can get command line arguments. That's how webpack, grunt, gulp, those command line tools, that's how they get the command line arguments such as options, such as some other arguments.

Then we can access the environmental variables. That's where the passwords, your database, IP address will be stored, your API keys. We can get that information from Node within Node.js from inside of your script. We can also get information about current uptime, about the memory usage. cwd(), it's...the results are a little bit different than __dirname.

cwd() or current working directory will get you the folder from which this currently running process was launched. And if you're running your node script.js, you're running from the same folder in which your source code is, cwd() would be the same as __dirname.

But if you're running from a parent folder or a subfolder, so not from the same folder in which your source code is, then cwd() would be different. And finally, we can exit the finished process or we can terminate another process. That would be handy when we would be talking about scalability and launching other processes.

Discussion
0 comments