In this post, we will take a look at how you would be able to incorporate Node.js into your Web Application. You are going to learn the usage of this from scratch as well as take a look at an example.
- a Web browser such as Chrome.
- Node.js above 12.x.x
- NPM install.
- Terminal ( I am using Hyper terminal in this post )
When you install Node it already comes with a bunch of modules. In this post we will take a look at one such built-in module and also we would take a look at how to incorporate external modules. We can use Node to get access to the local files of the computer too.
The link provided here takes us to the official Node.js File System Documentation page..
To illustrate the fact that Node can be used to manipulate the file-systems of your machine we will be taking a look at a method called copyFileSync() which copies the content from one file to the other.
In order to use the modules we first need to require the module. Now also create a simple text file called "file1.txt". Now write any sentence you like...
const fileSystem = require("fs"); // "fileSystem" is our constant and "fs" is the module. fileSystem.copyFileSync("file1.txt","file2.txt");
implement the same by typing "node index.js"
As you can see we have successfully implemented the file System Module and we have achieved the target of copying contents of one text file to the other. (ie from file1.txt to file2.txt)
NPM stands for Node Package Manager and it’s currently the world's largest collection of packages. Using NPM we could incorporate packages inside your projects saving us time and energy. Make sure that you are in the working directory. Now we are going to initialize NPM here by saying "npm init -y".
Now we will try to install a sample package called "animals" and try experimenting with it.
The link to the same is provided here. (https://www.npmjs.com/package/animals).
We will accomplish this in a very systematic step by step procedure as shown below:-
- Create a new folder.
- Using Hyper Terminal initialize NPM.
- Install the sample "animal" package by typing "npm install animals"
Now with that in place, we can verify that we have successfully installed the required packages by looking at our dependencies in our package.json file.
In this simple illustration we will try logging the names of animals in the console.
var animals = require("animals"); var animal1 = animals(); // animal1 stores a name of an amimal var animal2 = animals(); // animal2 stores a name of an amimal console.log("Name of my first animal is: " + animal1); console.log("Name of my second animal is: " + animal2);
Now just test your output using the Hyper Terminal.
I hope in this post you get the idea of how to work with Node Packages and incorporate any external modules too.
Link to my twitter: (https://twitter.com/rakshith_2209?lang=en)