PUBLISHED JANUARY 10, 2024
How much JavaScript do you need to learn NodeJS
In this series part, we explore the nuanced relationship between JavaScript and NodeJS, highlighting some subtle distinctions between the two environments.
Prerequisite
The transition from frontend to backend becomes seamless, making JavaScript a versatile language for full-stack development.
What is this JavaScript Runtime Environment? You may ask.
Well, a runtime environment is the environment provided to an application or software by the operating system.
In this environment, the application can send instructions or commands to the processor(s) to execute some operations like accessing system resources, such as RAM.
Normally, outside this environment, this wouldn't be possible since most programming languages are high-level languages (for example JavaScript).
The runtime environment also provides a state to your machine so that it can access resources such as software libraries, system variables, and environment variables, and also provides all the services and support needed for the processes involved in running the application or program.
`Too much jargon🤯? Don’t worry, it will make sense as you move forward. For now just digest what you can.`
NodeJs code is executed in a javaScript environment meaning node ships with all the javascript libraries.
As a is quick demonstration:
// Simple Node.js server that responds with a "Hello, Here is Node.js!" message.
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, Here is Node.js!');
});
server.listen(3000, () => {
console.log('Server running on http://localhost:3000/');
});
In the simple example above, we create a basic HTTP server using NodeJS, highlighting the familiar syntax, so loved by those familiar with JavaScript.
All that to say, to even begin with nodeJS, you have to be comfortable with the basics of javaScript development.
In order to quickly start with nodeJS and really enjoy the learning process, you must have a working knowledge of some advanced JavaScript concepts.
By how much exactly? You may ask.
Good question! Hold that in mind and let’s move on for now.
- Asynchronous Programming
Node.JS relies heavily on asynchronous operations. In fact, by default nodeJS is asynchronous.
Familiarity with or perhaps a mastery of JavaScript concepts like callbacks, promises, and async/await guarantees you a smooth experience with nodeJS and it’s APIs.
// Asynchronous operation with Promises
const fetchData = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Data fetched successfully!');
}, 2000);
});
};
fetchData().then((data) => {
console.log(data); // Output: Data fetched successfully!
});
// with async / await
const data = await fetchData()
console.log(data)
- Reusable Code
The ability to share code between the frontend and backend is a significant advantage. As an Advanced JavaScript developer, you can create reusable modules and libraries that seamlessly work in both environments.
For example, you can set up a module that exports two utility functions, one that sums two numbers and another that gives their difference. You can then import and use them on the frond-end app and server app(nodeJS).
- ES6+ Features:
NodeJS supports modern JavaScript features introduced in ES6 and later. Advanced JavaScript developers can leverage arrow functions, destructuring, and classes to enhance code readability and maintainability.
// ES6+ features
const numbers = [1, 2, 3, 4, 5];
const squaredNumbers = numbers.map((num) => num ** 2);
console.log(squaredNumbers); // Output: [1, 4, 9, 16, 25]
For a complete example, here is our basic node server setup using the ES6+ syntax.
// Importing modules
const http = require('http');
// Array Destructuring
const [, port = 3000] = process.argv;
// Arrow Function
const server = http.createServer((req, res) => {
// Template Literals
const message = `Server is running on http://localhost:${port}`;
// Spread Operator
const additionalInfo = {
date: new Date().toLocaleDateString(),
time: new Date().toLocaleTimeString(),
};
// Object Spread
const logInfo = { ...additionalInfo, message };
// Logging with Destructuring
const { date, time, message: logMessage } = logInfo;
console.log(`[${date} ${time}] ${logMessage}`);
res.end('Hello, World!');
});
// Class and Inheritance
class CustomServer extends http.Server {
constructor() {
super();
}
// Overriding the listen method
listen() {
// Using Promises
return new Promise((resolve, reject) => {
super.listen(port, (err) => {
if (err) reject(err);
resolve();
});
});
}
}
// Creating an instance of the custom server
const customServer = new CustomServer();
// Using async/await with Promises
async function startServer() {
try {
await customServer.listen();
} catch (error) {
console.error(`Error starting server: ${error.message}`);
}
}
// Starting the server
startServer();
At this point, you may be wondering if there are distinctions between nodeJS and JavaScript on the web.
Let's visit some more obvious distinctions.
- Environment Differences
JavaScript on the web primarily runs in browsers, while NodeJS operates on servers. Understanding the distinctions helps developers tailor their code for each environment.
What this means (in what mathematical terms) is;Javascript in Web = JS runtime + Web APIs
andNodeJS = JS runtime + NodeJS APIs
One such difference in APIs, I personally stumbled upon years ago, is the use of the popular javaScript string method replaceAll.
Prior to node 16, replaceAll was a web API only feature.
Try it for yourself. Switch between node versions starting from node version 8.
- Global Objects
Some global objects differ between the browser and NodeJS. Awareness of these distinctions is crucial for writing cross-compatible code.
For example
// Browser-specific code
if (window) {
console.log('Running in a browser environment');
}
// Node.js-specific code
if (global) {
console.log('Running in a Node.js environment');
}
There are many more of such distinctions, some quite obvious like DOM manipulation, Storage API etc… all of which are available only on the web.
Accessing the filesystem is seamless in NodeJS but requires explicit permission to be granted by the user on the web. File manipulation is also very advanced in NodeJS compared to the web.
Conclusion
To concluse, NodeJS and JavaScript form a powerful alliance, bridging the gap between frontend and backend development.
Aspiring NodeJS developers benefit immensely from a solid understanding of JavaScript, unlocking the full potential of both environments.
By embracing the non-linear nature of learning JavaScript and NodeJS, developers pave the way for creating end-to-end solutions using a single language: JavaScript.
I also recommend that you complete a full JavaScript tutorial first, then spend some time playing around it and when you feel comfortable enough with it, then you can embark on your journey to become a nodeJS developer.
EXTRAS:
If you are already familiar with other OOP languages and you'd rather jump straight into nodeJS, choosing the option to revisit JavaScript concepts on a need basis, then that's also possible.
Here are some concepts you are expected to know in order to have a smooth learning experience with nodeJS (well, at least according to the nodeJS team).
- ➢Expressions
- ➢Lexical Structure
- ➢Data Types
- ➢Classes
- ➢Variables
- ➢Functions
- ➢this operator
- ➢Arrow Functions
- ➢Loops
- ➢https://developer.mozilla.org/en-US/docs/Glossary/Scope
- ➢Arrays
- ➢Template Literals
- ➢Strict Mode
- ➢ECMAScript 2015 (ES6) and beyond
For Asynchronous programming:
In this series part, we talk about how much javascript is needed to learn nodeJS. From our discussion, it’s pretty clear that, to become a skilled nodeJS developer, you must first familiarize yourself with some basic and mid-level JavaScript concepts.
In the next part, we will revisit the V8 engine and discuss in detail the difference between NodeJS and the Browser.
Chapter 1 , Part 1 : Introduction to NodeJS
In this series part, I introduce nodeJS and some technical concepts associated with it. I also show how easy it is to setup and start a simple nodeJS web server.
Chapter 1 , Part 2 : How to Install and Setup NodeJS
In this series part, I run you through the various ways to install nodeJS. I also discuss how to install nvm and use it to switch between different node versions.
Chapter 1 , Part 3 : How much JavaScript do you need to learn NodeJS
In this series part, we explore the nuanced relationship between JavaScript and NodeJS, highlighting some subtle distinctions between the two environments.
Chapter 1 , Part 4 : The v8 Engine and the difference Between NodeJS and the browser
In this series part, we explore the V8 engine and how it interacts with nodeJS. We also discuss node’s event loop and uncover the mystery behinds node’s ability to handle concurrent operations.
Chapter 1 , Part 5 : NPM, the NodeJS package manager
Discover the essentials of npm, the powerful package manager for Node.js. Learn installation, management, publishing, and best practices
Chapter 1 , Part 6 : NodeJS in Development Vs Production
Explore how Node.js behaves differently in development and production environments. Learn key considerations for deploying Node.js applications effectively.
Chapter 2 , Part 1 : Asynchronous Flow Control
In this series part, we'll explore various aspects of asynchronous flow control in Node.js, from basic concepts to advanced techniques.
Chapter 2 , Part 2 : Blocking vs Non-blocking I/O
Explore the differences between blocking and non-blocking I/O in Node.js, and learn how to optimize performance and scalability.
Chapter 2 , Part 3 : Understanding NodeJS Event loop
Exploring the Node.js event loop by understanding its phases, kernel integration, and processes enabling seamless handling of asynchronous operations in your applications.
Chapter 2 , Part 4 : The NodeJS EventEmitter
Explore the power of Node.js EventEmitter: an essential tool for building scalable and event-driven applications. Learn how to utilize it effectively!
Chapter 3 , Part 1 : Working with files in NodeJS
Gain comprehensive insights into file management in Node.js, covering file stats, paths, and descriptors, to streamline and enhance file operations in your applications.
Chapter 3 , Part 2 : Reading and Writing Files in NodeJS
Uncover the fundamentals of reading and writing files in nodeJS with comprehensive examples and use cases for some widely used methods.
Chapter 3 , Part 3 : Working with Folders in NodeJS
Unlock the secrets of folder manipulation in Node.js! Explore essential techniques and methods for working with directories efficiently
Chapter 4 , Part 1 : Running NodeJS Scripts
Master the command line interface for executing nodeJS scripts efficiently. Learn common options and best practices for seamless script execution
Chapter 4 , Part 2 : Reading Environment Variables in NodeJS
Learn how to efficiently manage environment variables in nodeJS applications. Explore various methods and best practices for security and portability
Chapter 4 , Part 3 : Writing Outputs to the Command Line in NodeJS
Learn essential techniques for writing outputs in nodeJS CLI. From basic logging to formatting and understanding stdout/stderr.
Chapter 4 , Part 4 : Reading Inputs from the Command Line in NodeJS
Learn the various ways and strategies to efficiently read command line inputs in nodeJS, making your program more interactive and flexible.
Chapter 4 , Part 5 : The NodeJS Read, Evaluate, Print, and Loop (REPL)
Explore the power of nodeJS's Read, Evaluate, Print, and Loop (REPL). Learn how to use this interactive environment for rapid prototyping, debugging, and experimentation.
Chapter 5 , Part 1 : Introduction to Testing in NodeJS
Discover the fundamentals of testing in nodeJS! Learn about testing types, frameworks, and best practices for building reliable applications.
Chapter 5 , Part 2 : Debugging Tools and Techniques in NodeJS
Explore essential debugging tools and techniques in Node.js development. From built-in options to advanced strategies, and best practices for effective debugging.
Chapter 6 , Part 1 : Project Planning and Setup
Discuss the planning and design process for building our interactive file explorer in Node.js, focusing on core features, UI/UX design, and implementation approach and initial setup.
Chapter 6 , Part 2 : Implementing Basic functionalities
In this guide, we'll implement the basic functionalities of our app which will cover initial welcome and action prompts.
Chapter 6 , Part 3 : Implementating Core Features and Conclusion
In this guide, we'll complete the rest of the more advanced functionalities of our app including, create, search, sort, delete, rename and navigate file directories.