How to Install Node.js: NPM Setup & First Script Execution
(Node Series Part 2)
In this, I will share methods on how to install Node and other basics of Node.js.
In this, I have avoided using third-party packages like Express as the idea is to learn the basics without the help of packages.
Installation
To install Node.js, visit the following website.
There are many more efficient ways to use Node Version Manager.
Now download NVM(Node Version Manager), which helps a lot to download different versions of Node.js and use them.
Here is a reference guide on how to install nvm on your system
Usage
Initially, to test out you can create a file with any name in JS and directly run that using Node.js
Let’s create a file index.js, and run it
console.log("test")Now, run the file using the following command on your terminal
node index.jsNow let’s create a node project, run the following command
npm inityou will get the following interface now
Fill up the details
These object details will be inside your package.json,
add index.js, which will be the entry point for your Node project as specified in the package.json; if needed, it can be changed.
Now u can directly install all the packages required for your project using npm(Node Package Manager). There are other package managers also, ex. yarn.
To run this project, you can just use the above command as the same
node index.jsSo now you have set up your simple Node.js project.
Node REPL
REPL (Read-Eval-Print-Loop), which allows you to execute JavaScript code interactively in a terminal.
To use this, just run the node in the terminal
nodeYou will now get an interactive terminal, something like this,s where u can write JS and try it
We can also trigger REPL using code. Well, it’s just a tool to help node on the terminal. you call also get the packages and all node code here.
The Node REPL is similar to a command-line interface for JavaScript. It is an interactive environment where you can enter JavaScript code and see the results immediately. It is great for testing out small pieces of code or experimenting with new features.
đź§ŞBenefits of Using the Node REPL
- Great for quickly testing ideas or code snippets.
- Useful for debugging and experimenting with new features.
- Handy for prototyping small pieces of code before adding them to a larger project.
⚠️Limitations of the Node REPL
- Not suitable for writing large or complex programs.
- Lacks features of a full development environment, such as code navigation, linting, version control, or project structure.
- Does not replace a proper IDE or code editor.
âś… Best Practice
- Use the Node REPL as a companion tool, not a primary workspace.
- Combine it with a robust development setup for the best productivity and code quality.
Browser VS Node
Now, what is the difference between JavaScript in the browser and Node.js?
Global Object
In a browser, the global object is window, while in Node.js, it is global. For example, to log the global object in a browser, we can use:
console.log(window);console.log(global);Now, to avoid confusion, what we use is globalthis, which is the same as window and global on the node and browser.
In Node.js
using globalthis in node
In browser
On the browser, you can check
So basically, globalthis is for full-stack developers, as this key can be used in a browser or node, as it switches context where it is being used, will become window or global depending on where it is being used.
Modules
Inside Browser: We can import modules in the browser using script tags with the type attribute set to module and the src attribute set to the path of the module file.
Get Shubham Gupta’s stories in your inbox
Join Medium for free to get updates from this writer.
For example:
<script type="module" src="./app.js"></script>Now, to use it inside your JS file, simply
import { sayHello } from './module.js'
sayHello();Inside Node: Now in Node.js js we have two module ways called CommonJS(older way) and ESM
Inside the node, you just need to use it once
import { module } from './module.js';DOM
DOM is only present in the browser, not in Node.
Console.log
This is not part of the browser, it is a WEB api provided when used there.
While in Node.js, it is just a wrapper written by its creator, the original console was this
process.stdout.write("your text ") // try on node While the wrapper contains far more functionality.
Art Of Logging
Let’s say inside the console, u get to see data on the terminal when the console in Node.js, what if we console an object? What will happen then?
Here inside our index.js file
let obj = {
name: "Shubham",
add: {
city: "city",
satate: "state",
pincode: { area: "area", pin: "123",
country: { name: "country", } }
}
}
console.log(obj)As you can see above, the entire object is not fully displayed in this.
Solutions for this :
1- We can solve this by using the console.dir()
let obj = {
name: "Shubham",
add: {
city: "city",
satate: "state",
pincode: { area: "area", pin: "123",
country: { name: "country", } }
}
}
console.dir(obj,{depth:null,colors:true})2- Stringify it
Now, above u can see the data is there, but the indentation is gone, so we can pass some parameters to make it proper
console.log(JSON.stringify(obj,null,2))
// where second argument is the replacer fucntion.
// third is the space to provide at indentation3. consoe.table()
although we don’t use it not that practical.
Now above methods can be moved inside a utility file and be reused again.
In Node.js js we do need logging for debugging and to know the state of the data at the desired point and we need to keep the logs so that we can look them later if we restart the system the log will be gone.
For this, we have packages that help in maintaining the logs and also print nested library
examples, Pino, and Winston
How to debug node code
Never Ever Rely on console.log or debugger in production.
When an issue comes up, you might have to scroll endlessly or if the server restarts, all logs are gone, plus when issues come, you might not be there to add breakpoints and check. Adding breakpoints in production is madness.
Solutions:
- Add your logs to a file, use Winston. Or always use a library that preserves your log.
- Debug in Chrome , u can add a flag — inspect on the node while running it to debug
node --inspect index.jsHere as server needs to be running to make inspect work
here I have added a small server for the demonstration only. Create a server.js file add this
const http = require('http');
const PORT = 3000;
const server = http.createServer((req, res) => {
// Log incoming requests
console.log(`${req.method} ${req.url}`);
// Dummy endpoint: GET /hello
if (req.method === "GET" && req.url === "/hello") {
console.log(`Uptime: ${process.uptime()} seconds`);
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ message: "Hello, world!" }));
return;
}
// Fallback for other endpoints
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("Not Found");
});
server.listen(PORT, () => {
console.log(`🚀 Server running at http://localhost:${PORT}`);
});now run the inspect command
node --inspect server.jsTo open the debugger, just inspect any page. In the browser, u will see the node Icon and click on it
simply go to sources and your running files in the server will be there where u can add the breakpoints
Now there is another way also to open this simply type this in the browser URL chrome://inspect/
and click on inspect
It will open the same
3. Use VS Code
in vs code select the file and click on run debugger
once you do u will see same panel as the browser and u can add breakpoints on the file
It is better to use logs for debugging, which will maintain a record so that anyone else can easily debug and find the issue by checking the logs.
If you’d like to be in the know, subscribe, clap, like and share. Cheers!







