Node is purely JavaScript, if you are already familiar with JavaScript coding, then you may find it super easy , there is no different in syntax, however , in node you learn many other additional syntax with many different objects.
If you are learning node js for the first time, go through my earlier node js post.
To write a node js code you need some editor, there are many free editors are available, but I suggest visual studio code editor (because i am .net developer :) ), VS Code is super easy to use and very popular.
Now to write code just open your editor and create a file with .js extension and save it, then start with simple code like assigning value to a variable
var _message="Hello World"; console.log(_message);
Like any other programming language, in nodejs we have single line comment using double slash like //
and multiline comments using single slash with star like /* */
.
Here is an example of how to work with date function in node code, get current date, time, year etc just like JavaScript code
var today=new Date(); console.log(today.getDate()); console.log(today.getDay()); console.log(today.getFullYear()); console.log(today.getHours()); console.log(today.getMinutes()); console.log(today.getSeconds());
Here is an example of how to concatenate string variables in Nodejs, we also can format string in node js, specially sometimes when we need to put variables inside a string.
var st1 ="Hello,"; var st2="How are you doing?"; console.log(st1 + st2);
There is another better way to format string in nodejs.
You need to install util module by executing npm install util
command, then use util.format function like example below.
var myText = "Today is %s, We are at %s "; var result = util.format(myText, 'Sunday', 'Goa'); console.log(result); //The output will look like Today is Sunday, We are at Goa
The node util module provide lots of commonly used functionalities like text encoder, decoder, type check etc.
To access any module in node js, you need to add the reference in the file like example below, make sure the module is installed in current directory cd project-folder
., otherwise you need to install the module using npm command like npm install module-name
const util = require('util');
This is more like adding namespace reference, you can add any number of reference based on your requirement.
You can start looking at following examples for better understanding.