How To Write Your First Node.js Script
Tags: node, javascript, developer
Published: 2021-06-08 12:31:50

# Introduction

Until recently(if you think that 2009 is recently), we could only run JS code in a web browser. Node is a JavaScript runtime that executes code outside of the browser. We can use the same JS syntax we know and love to write server-side code, instead of relying on other languages like Python or Ruby. You can build Web Servers, Command Line Tools, Native Apps(VSCode is a Node app!), Video Games, Drone Software, and a whole lot more.

In this post, I am going to show you how to write your first little Node script which will make you a directory with an HTML, CSS, and JavaScript file in it.

# Getting Started

First, you need to check if you have Node installed on your machine. If you don't know if you have it, just go to the terminal and write:
```
node -v
```

This will print out the Node.js version which is currently installed. If you see an error and nothing prints, then you don't have Node installed.

In order to install Node, go to the node website and just press the download button.

[https://nodejs.org/en/](https://nodejs.org/en/)

After installing Node, we need to create a JavaScript file. Let's call this file `script.js`. In this file, we are going to write our script.

Now that we have Node installed and our file created, it's time to write our script. For this script, we are going to need to know what the `process` object is and how the `fs` module works. 

# How To Run Node Files

In order to run Node files, you just need to write `node` and then the file name next to it in the terminal. Th file must be in the same folder that you're in, or you need to reference that full path relative to where you are at the moment. 

```
node script.js
```

# `process` & `argv`

`process` is an object that's available which is in the global scope. It provides information about, and control over, the current Node.js process. It has a bunch of methods and properties. For example, we can see our current working directory. 

```
process.cwd()
```

There is a method called `process.argv`. It returns an array containing the command line arguments passed when the Node.js process was launched. The first element will be the path where the node executable is, and the second will be the path to the JS file being executed. To call this method you need to go to your JS file and `console.log()` it.

```
console.log(process.argv);
```

Then after running your file, you should see this:

```
node script.js
[ '/usr/local/bin/node', '/Users/ghostman/scripts/script.js' ]
```

Any remaining element will be additional command-line arguments. We can pass them as arguments into a script. Not a function, but it's a similar idea. I can pass in arguments to a script. 

Here is an example of a little script that prints out the additional command-line arguments:

```
const args = process.argv.slice(2)  -> slice to remove first two items.

for(let arg of args){
    console.log(`Hello ${arg}`)
}
```

Then when we run the file like this:

```
node script.js Batman Superman
```

Ou output should look like this:

```
Hello Batman
Hello Superman
```

This is a fun little script to help you understand how the file and node work together and how they can be used. 

Now let's get to the fun part.

# `fs` Module

The fs module enables interacting with the file system. It has hundreds of methods that you can use. Here is a list so you can see how much they are.

[https://nodejs.org/dist/latest-v14.x/docs/api/fs.html](https://nodejs.org/dist/latest-v14.x/docs/api/fs.html)

In order for us to use the `fs` module, we have to `require` it. We have to save it in a variable.

```
const fs = require('fs')
```

Now that we have our `fs` module, here are the methods that we will be needing for our script.

### `fs.mkdirSync`

This method creates a directory in our current working directory. There is also an `fs.mkdir` method, but we will be using the synchronous method because it will not execute anything else until this method is completed. Here is an example of our method:

```
fs.mkdirSync('dirName')
```

### `fs.writeFileSync`

This method creates files for us. Just like `fs.mkdirSync`, this method will not let anything else run until it has finished its process. 

```
fs.writeFileSync('fileName')
```

You can check for errors with the `try..catch` statements if your code doesn't seem to work.

```
try {
    fs.writeFileSync('fileName')
} catch (e){
    console.log(e)
}
```
# Writting Our Node Script

Now that you have a basic knowledge of Node, try writing a script that creates a directory with three files inside it on your own. If you can't, that OK. Here is how to write your script:

First, you need to require the `fs` module. Then you must use `process.argv` to set the name of your directory. After that, you need to use the `fs.mkdirSync` method and the `fs.writeFileSync` method to create the directory and the files:

```
const fs = require('fs')
const folderName = process.argv[2] || 'Project'

try {
    fs.mkdirSync(folderName);
    fs.writeFileSync(`${folderName}/index.html`);
    fs.writeFileSync(`${folderName}/style.css`);
    fs.writeFileSync(`${folderName}/app.js`);
} catch (err) {
    console.log(`Error!`);
console.log(err)
} 
```

After writing the code for the script, we can run it like this:

```
node script.js SecretProject
```

If we don't give an additional command-line argument, it will automatically set the directory name to `Project`.

# Consclusion

I hope that this post has helped you understand Node.js a little bit more and made you more comfortable with it. Don't be scared to try some new stuff and experiment with all those `fs` module methods.

Let me know if this has been of help to you through Twitter. You can follow me [here](https://twitter.com/bo_iliev21).