DEV Community

loading...
Cover image for How To Write Your First Node.js Script

How To Write Your First Node.js Script

Boyan Iliev
I am an 18-year-old high schooler, that loves web development and is looking forward to his journey as a developer.
Originally published at devdojo.com ・4 min read

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
Enter fullscreen mode Exit fullscreen mode

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/

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
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

Then after running your file, you should see this:

node script.js
[ '/usr/local/bin/node', '/Users/ghostman/scripts/script.js' ]
Enter fullscreen mode Exit fullscreen mode

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}`)
}
Enter fullscreen mode Exit fullscreen mode

Then when we run the file like this:

node script.js Batman Superman
Enter fullscreen mode Exit fullscreen mode

Ou output should look like this:

Hello Batman
Hello Superman
Enter fullscreen mode Exit fullscreen mode

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

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')
Enter fullscreen mode Exit fullscreen mode

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')
Enter fullscreen mode Exit fullscreen mode

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')
Enter fullscreen mode Exit fullscreen mode

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)
}
Enter fullscreen mode Exit fullscreen mode

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)
} 
Enter fullscreen mode Exit fullscreen mode

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

node script.js SecretProject
Enter fullscreen mode Exit fullscreen mode

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.

Discussion (5)

Collapse
bobbyiliev profile image
Bobby Iliev

Great post! Keep it up brother!

Collapse
boiliev profile image
Boyan Iliev Author

Thanks bro.

Collapse
asciiden profile image
Denislav Gavrilov πŸ‘¨β€πŸš€πŸ€–πŸ€·β€β™‚οΈ

Sick! I was just looking for a way to get back to Node!

Collapse
vishalraj82 profile image
Vishal Raj

I believe this article might of some help as well - dev.to/vishalraj82/nodejs-run-your...

Collapse
boiliev profile image
Boyan Iliev Author

Great post!