This allows Node.js to be very performant. A Node.js app runs in a single process, without creating a new thread for every request.
- When Node.js performs an I/O operation, like reading from the network, accessing a database or the filesystem, instead of blocking the thread and wasting CPU cycles waiting, Node.js will resume the operations when the response comes back.
- This allows Node.js to handle thousands of concurrent connections with a single server without introducing the burden of managing thread concurrency, which could be a significant source of bugs.
- In Node.js the new ECMAScript standards can be used without problems, as you don't have to wait for all your users to update their browsers - you are in charge of deciding which ECMAScript version to use by changing the Node.js version, and you can also enable specific experimental features by running Node.js with flags.
- npm with its simple structure helped the ecosystem of Node.js proliferate, and now the npm registry hosts over 1,000,000 open source packages you can freely use.
- The most common example Hello World of Node.js is a web server:.
- This code first includes the Node.js http module. Node.js has a fantastic standard library, including first-class support for networking.
The createServer() method of http creates a new HTTP server and returns it. The server is set to listen on the specified port and host name.
8. Node.js Webserver with Express
When the server is ready, the callback function is called, in this case informing us that the server is running. Whenever a new request is received, the request event is called, providing two objects: a request (an http.IncomingMessage object) and a response (an http.ServerResponse object).
Those 2 objects are essential to handle the HTTP call. The first provides the request details. In this simple example, this is not used, but you could access the request headers and request data.
The second is used to return data to the caller. In this case with:. we set the statusCode property to 200, to indicate a successful response. We set the Content-Type header:.
and we close the response, adding the content as an argument to end():. Node.js is a low-level platform. In order to make things easy and exciting for developers, thousands of libraries were built upon Node.js by the community.
Many of those established over time as popular options.
A Vast Number of Libraries
Here is a non-comprehensive list of the ones worth learning:. AdonisJS: A TypeScript-based fully featured framework highly focused on developer ergonomics, stability, and confidence. Adonis is one of the fastest Node.js web frameworks.
Egg.js: A framework to build better enterprise frameworks and apps with Node.js & Koa. Express: It provides one of the most simple yet powerful ways to create a web server.
When to not use Node.js
Its minimalist approach, unopinionated, focused on the core features of a server, is key to its success. Fastify: A web framework highly focused on providing the best developer experience with the least overhead and a powerful plugin architecture.
Build prototypes in minutes and production-ready apps in days. Gatsby: A React-based, GraphQL powered, static site generator with a very rich ecosystem of plugins and starters.
- hapi: A rich framework for building applications and services that enables developers to focus on writing reusable application logic instead of spending time building infrastructure.
- koa: It is built by the same team behind Express, aims to be even simpler and smaller, building on top of years of knowledge.
- The new project born out of the need to create incompatible changes without disrupting the existing community.
- Loopback.io: Makes it easy to build modern applications that require complex integrations.
- Once an off-the-shelf tool that provided everything, now integrates with frontend libs React, Vue, and Angular.
- Can be used to create mobile apps as well.
Micro: It provides a very lightweight server to create asynchronous HTTP microservices. NestJS: A TypeScript based progressive Node.js framework for building enterprise-grade efficient, reliable and scalable server-side applications.
Next.js: React framework that gives you the best developer experience with all the features you need for production: hybrid static & server rendering, TypeScript support, smart bundling, route pre-fetching, and more.
Nx: A toolkit for full-stack monorepo development using NestJS, Express, React, Angular, and more!
Nx helps scale your development from one team building one application to many teams collaborating on multiple applications!
Remix: Remix is a fullstack web framework for building excellent user experiences for the web.
Sapper: Sapper is a framework for building web applications of all sizes, with a beautiful development experience and flexible filesystem-based routing.
Offers SSR and more! Socket.io: A real-time communication engine to build network applications. Strapi: Strapi is a flexible, open-source Headless CMS that gives developers the freedom to choose their favorite tools and frameworks while also allowing editors to easily manage and distribute their content.
By making the admin panel and API extensible through a plugin system, Strapi enables the world's largest companies to accelerate content delivery while building beautiful digital experiences.
The modern web application has really come a long way over the years with the introduction of many popular frameworks such as bootstrap, Angular JS, etc.
But when it came to developing server-based applications, there was a kind of void, and this is where Node.js came into the picture.
Questions still open? – Node.js FAQ
Node.js is based on an event-driven architecture and a non-blocking Input/Output API that is designed to optimize an application’s throughput and scalability for real-time web applications.
10. Deploy (publish) Node.js app
Over a long period of time, the framework available for web development were all based on a stateless model.
A stateless model is where the data generated in one session (such as information about user settings and events that occurred) is not maintained for usage in the next session with that user.
A lot of work had to be done to maintain the session information between requests for a user. But with Node.js, there is finally a way for web applications to have real-time two-way connections, where both the client and server can initiate communication, allowing them to exchange data freely.
We will have a look into the real worth of Node.js in the coming chapters, but what is it that makes this framework so famous.
Over the years, most of the applications were based on a stateless request-response framework. In these sort of applications, it is up to the developer to ensure the right code was put in place to ensure the state of web session was maintained while the user was working with the system.
But with Node.js web applications, you can now work in real-time and have a 2-way communication.
The state is maintained, and either the client or server can start the communication. Let’s look at some of the key features of Node.js. Asynchronous event-driven IO helps concurrent request handling – This is probably the most significant selling point of Node.js.
This feature basically means that if a request is received by Node for some Input/Output operation, it will execute the operation in the background and continue with processing other requests.This is quite different from other programming languages.
But in the case of Node.js the important fraction of code to notice is the declaration of the function (‘function(error,data)’).
This is known as a callback function. So what happens here is that the file reading operation will start in the background. And other processing can happen simultaneously while the file is being read.
Handling of concurrent requests – Another key functionality of Node is the ability to handle concurrent connections with a very minimal overhead on a single process.
There is an active and vibrant community for the Node.js framework.
- Because of the active community, there are always keys updates made available to the framework.
- Node.js is used by many large companies.
- LinkedIn – LinkedIn is using Node.js to power their Mobile Servers, which powers the iPhone, Android, and Mobile Web products.
- Node.js is best for usage in streaming or event-based real-time applications like.
This helps to keep the framework always up-to-date with the latest trends in web development.
Below is a list of a few of them. Paypal – A lot of sites within Paypal have also started the transition onto Node.js.
Mozilla has implemented Node.js to support browser APIs which has half a billion installs.
eBay hosts their HTTP API service in Node.js.
Chat applications. Game servers – Fast and high-performance servers that need to processes thousands of requests at a time, then this is an ideal framework.
- Good forcollaborative environment – This is good for environments which manage documents.
- So Node.js is good for these environments because the event loop in Node.js can be triggered whenever documents are changed in a document managed environment.
- Streaming servers – Another ideal scenario to use Node is for multimedia streaming servers wherein clients have request’s to pull different multimedia contents from this server.
- Node.js can be used for a lot of applications with various purposes.
In a document management environment, you will have multiple people who post their documents and do constant changes by checking out and checking in documents.
Advertisement servers – Again here you could have thousands of request to pull advertisements from the central server and Node.js can be an ideal framework to handle this.
Node.js is good when you need high levels of concurrency but less amount of dedicated CPU time.
The only scenario where it should not be used is where there are long processing times, which is required by the application.
As discussed above, Node.js is used best where processing needs less dedicated CPU time.
Installing on Node.js on Windows or on Windows Subsystem for Linux.
Open your command line and create a new directory: mkdir HelloNode, then enter the directory: cd HelloNode.
Open the directory and your app.js file in VS Code using the command: code .
Add a simple string variable ("Hello World"), then send the contents of the string to your console by entering this in your "app.js" file:.
Node.js Frameworks and Tools
To run your "app.js" file with Node.js. Open your terminal right inside VS Code by selecting View > Terminal (or select Ctrl+`, using the backtick character). If you need to change the default terminal, select the dropdown menu and choose Select Default Shell.
Create a new project folder: mkdir ExpressProjects and enter that directory: cd ExpressProjects.
Use Express to create a HelloWorld project template: npx express-generator HelloWorld --view=pug. We are using the npx command here to execute the Express.js Node package without actually installing it (or by temporarily installing it depending on how you want to think of it).
If you try to use the express command or check the version of Express installed using: express --version, you will receive a response that Express cannot be found.
If you want to globally install Express to use over and over again, use: npm install -g express-generator.
You can view a list of the packages that have been installed by npm using npm list.
They'll be listed by depth (the number of nested directories deep).
Packages that you installed will be at depth 0. That package's dependencies will be at depth 1, further dependencies at depth 2, and so on.
To learn more, see Difference between npx and npm?
on StackOverflow. Examine the files and folders that Express included by opening the project in VS Code, with: code .
The files that Express generates will create a web app that uses an architecture that can appear a little overwhelming at first.
Contains all the route handlers for the application. Two files, index.js and users.js, are automatically generated in this folder to serve as examples of how to separate out your application’s route configuration.
Contains the files used by your template engine.
Install the Express package dependencies with:. At this point you have the framework set up for a multiple-page web app that has access to a large variety of APIs and HTTP utility methods and middleware, making it easier to create a robust API.
Start the Express app on a virtual server by entering:.
The DEBUG=myapp:* part of the command above means you are telling Node.js that you want to turn on logging for debugging purposes.
Remember to replace 'myapp' with your app name.
and selecting Save (Ctrl+S). View your change by refreshing the localhost:3000 URL on your web browser. To stop running your Express app, in your terminal, enter: Ctrl+C.
In your command line, open the Node.js CLI. You'll see the > prompt letting you know you're using Node.js after entering: node.
To identify the operating system you are currently using (which should return a response letting you know that you're on Windows), enter: os.platform().
To check your CPU's architecture, enter: os.arch(). To view the CPUs available on your system, enter: os.cpus().
Why use Node.js?
Leave the Node.js CLI by entering .exit or by selecting Ctrl+C twice.
You can use the Node.js OS module to do things like check the platform and return a platform-specific variable: Win32/.bat for Windows development, darwin/.sh for Mac/unix, Linux, SunOS, and so on (for example, var isWin = process.platform"win32";).
This Node.js tutorial is aimed at developers who want to program with Node.js but know little or nothing about it yet – i.e.
complete beginners in this field.Advertisements. Node.js is becoming more and more popular: Especially when it comes to creating Rest APIs, Node is way out in front.
This Node.js tutorial is very practical and with some examples.
Nevertheless, I will briefly discuss the functionality, application and installation at the beginning.
From chapter 3 on we will start with the practical part.
In this tutorial you will learn the following:.
Table of Contents−5.
Create first Node.js App8. Node.js Webserver with Express. Create first Node.js App.
Node.js Webserver with Express.
With Node.js, however, it is now possible to develop everything from small CLI (command line) tools to complex programs and standalone HTTP servers.
Exactly this universal applicability makes Node.js so ingenious for me personally – and also for many other developers!
MySQL or MongoDB).Advertisements. So Node.js acts as a kind of web server.
If you are now wondering if you really need and want to be able to use Node.js, you should read through the most frequently asked questions below and decide if Node.js is the right technology for you.
Another important reason for the success are the on-board tools that come with Node.js. From the ground up, Node.js already has many features and modules that are easy to use.
And to make it even more perfect, there is the package manager – also called npm (Node Package Manager).
On Windows, you can simply download the installer and follow the installation instructions.
It is best to download the LTS (Long-term support) version, as this is already established and has fewer bugs than the latest version. On the Mac, just like on Windows, you can download the official installer and follow the installation instructions.
Again, it is best to download the LTS (Long-term support) version, as this is already established and has fewer bugs than the latest version.
Features of Node.js
Depending on the Linux distribution you choose the appropriate installation command. CLI stands for Command-Line Interface and means command line.
On the Mac you can use the pre-installed program “Terminal” and on Windows the command prompt (cmd.exe). The CLI can be used to launch Node.js applications, install modules, and view error messages and log output.
In the further course of this article you now know what you can understand by the CLI.
If you work with Node.js, you will always use modules from other developers.Advertisements.
Security vulnerabilities are (usually) closed promptly and you can update such a dependency with a command.
Standardization ensures easier handling between multiple developers.
Good documentation on existing interfaces. In this example we download the module express. This works with the following command:.
If you use the --save-dev parameter, these are created as dev dependencies – i.e.
- only required for development.
- When you install a module, a corresponding entry is created in the package.json and the folder node_modules is created automatically.
- This contains all installed modules and can be ignored by you for now.
AdvertisementsTip: If you work with git, for example, you can exclude the node_modules folder in your .gitignore.
The folder can be recreated using the npm install command when you load your project on a different device.
You can simply use this command:Advertisements. The time has come, we are finally starting to program.
To create a Node.js project, we simply create a normal folder in any directory. In it we create an index.js, which is our start file.
You can fill in these fields or like me just leave them on default settings.
The first code is written and we want to start our program.
If you install packages, they will also appear in this list.
Under scripts you can create your own scripts, e.g.
What is Node.js?
to execute test routines automatically or to automate other tasks.
If you want to learn more about this, have a look at this tutorial. It’s really annoying when we have to manually restart our Node.js app after every small change to the code, right?
Right, that’s why there is a module called nodemon which we install globally. This module detects file changes and restarts the Node.js app within milliseconds.
This speeds up our workflow tremendously.
- After the installation we start Nodemon via this command and directly our app is started and automatically restarted in case of changes.
- Now when you save your files inside the project folder, the Node.js app will automatically restart.
I don’t want to deprive you of one very central function: Environment variables.
They are quite an important thing when it comes to variable properties like credentials, configuration email addresses or file paths.
Here is an example:. You have a local database running on your local PC with the user test and the password 123456 (hopefully not 🙂 ).
If you want to connect to it with your Node.js application, you would have to include these credentials statically in your source code.
But on your production system you have completely different credentials. So no connection can be established. And using the same credentials is not an option, because it is insecure, sometimes not feasible and also in cases like changing file paths not feasible at all.
On our live system we can then work with completely different values without having to adapt our source code.
For the development we use the package dotenv(npm install dotenv --save-dev) and create the file .env in our main directory and write there one variable with value per line.
To access it in our Node.js app, we need the line highlighted in red.
Via process.env.VARIABLE we can then retrieve the corresponding value.
Attention: The .env file should not be uploaded to your git repository and should not be made public, because it may contain sensitive access data!
- Just add the file to your .gitignore.
- When our application is running on a production system, the .env file is no longer needed.
- The environment variables are then set in other places – this varies depending on the hosting.
- In my Plesk hosting this view looks like this:.
We can now write and execute functions and output texts from the console. However, the user of our application has nothing of this, since he can only access it via the browser.
We use the variables req and res in front of it in the code. When you call a website, a GET request is executed in the background.
But there are many more types, which are especially important for the development of Rest APIs.
Here are the most important ones in short form:.
GET: Requests resources from the server.
POST: Sends data (e.g. in the request body) with which the server is to create a new resource.
PUT: Also sends data to the server with which it should update an existing resource. DELETE: Deletes a resource from the server. Resources can be very different things: a temporary object, an entry from a database or a simple file.
- It depends on your application.
- A list of all available HTTP request methods can be found here.
- If you want to know more about HTTP request methods, I can recommend this article.
- In this tutorial we will only use the GET method.
- You can find more tutorials at the end of this post.
When to Use Node.js
Now, if we adjust our route a little bit, we can return data that has already been passed:.
Who uses Node.js
This approach is the basis for creating a Rest API. Meanwhile, you should also always test your application directly for anomalies and write test cases.
1. What is Node.js?
This convention is important to avoid sharing private/sensitive code.
As second parameter we can specify an array with further options.
There we pass the property root with the constant __dirname.
5. Create first Node.js App
This contains the current path where the JS file is located. Around it we have a try-catch block in case the file cannot be read.
If we now call http://localhost:3000/html-example, our static HTML page appears.
To deploy Node.js apps with Plesk you can find a tutorial here. Quite a lot of information at once, isn’t it?
Nevertheless, I hope you got a good impression of what’s possible with Node.js and that I made you curious for more.
If you have any unanswered questions, feel free to post them in the comments!
On my blog you can find many more tutorials and articles about Node.js.
Scroll down a little bit, there you will see more posts.
If you want to start with the development of Rest APIs I can already recommend this tutorial.
An Example Node.js Application
This allows us to further improve the user experience for this website in the future. You can change or revoke your consent at any time.
- cookie-state: Contains the setting of this cookie-view (Runtime: 7 days, Provider: Site owner).
- pll_language: Contains the setting of the language (Runtime: 1 year, Provider: Site owner).
- theme: Contains the setting of the theme (light oder dark) (Runtime: 30 days, Provider: Site owner).
- voted_posts: Contains the setting about the passed feedback to the posts (Runtime: 30 days, Provider: Site owner).
mtm_consent_removed: Is set by the tracking tool Matomo to save that you do not want to be tracked.
4. Node.js Packages (Modules)
(Runtime: 30 years, Provider: Matomo). Statistics, Marketing, External Media. You can list and change individual cookies here.
It is used to develop I/O intensive web applications like video streaming sites, single-page applications, and other web applications.
Node.js is open source, completely free, and used by thousands of developers around the world.
This tutorial is designed for software programmers who want to learn the basics of Node.js and its architectural concepts.
This tutorial will give you enough understanding on all the necessary components of Node.js with suitable examples.
97 Lectures 6 hours . Join 426+ developers already learning Nodejs Beginner tips & tricks. After building hundreds of Node.js APIs, backends, and CLIs used bymillions of developers, I am sharing exactly how you can do it yourself with minimum effective effort.
Learn Node.js from scratch.
9. Reading files with Node.js
Build scalable realtime systems with production-grade APIs and CLIs. Impress your manager andhelp the community.→ I'm sharing it all in this online video course.
Or if you're already convinced pre-order nowat 10% off! Full-time #OpenSourcerer Google Developers Expert Web Dev Advocate Node.js Community Committee Member Author of variousopen-source dev-tools and software libraries used by millions of developers worldwide (inc.
engineers at Google, AWS, Microsoft, Intel, HP…) TEDx Speaker Regular WordPress Core Developer Member of SmashingMagazine Experts Panel, Featured/published author at CSS-Tricks, Tuts+, Scotch.io, TorqueMag, SitePoint… A Self-confessed hilarious comedian.
Check out his work oncorona-cli,Shades of Purple theme,wp-continuous-deployment,create-guten-block,Emoji Log, and many moreopen-source projectson GitHub.
I've already started recording this course. This is for both absolute beginners to advanced developers.
Tweet me at @MrAhmadAwais →. ACCESS:All Modules. VIDEOS:Every Course Video.
EXPIRY:Single One-time Payment. UPDATES:Free Lifetime Course Updates.
EXAMPLES:Over 10 Node.js CLI Projects. COMMUNITY:Free Access to Private Slack. EVERYTHING:Including all lessons & modules.
VALUE FOR MONEY:14 days refund (no Q/A).
10% OFF if you pre-order now! Price excludes tax VAT/GST. 426 ALREADY SOLD.
You don't have to take my word for it. Some nice folks have said some nice things! Shit, I didn't know that!!!!!!! This tip is life changing to me!!
Ahmad's Open Source: "It's very impressive".
— Won Automattic Design Award Trophy. The create-guten-block project is an awesome awesome contribution to the community — at AWP Gutenberg series.
I've been using VSCode for a few months and I'm not a power user at all.
It's a fun theme, and it's easy to read! Kudos to the teacher @MrAhmadAwais for making the #VSCODEpro learning a breeze.
I am on the 14th chapter and this is getting as exciting as a binge learning. Ahmad, your hard work is making a student's life easy.
You deserve great respect. I always find him to be an excellent communicator, highly skilled, considerate, and extremely generous.
Introduction to Node.js
He's a pleasure to collaborate with and he's produced some very impressive public and FREE #OpenSource work for developers to learn and benefit from.
In my book, those are some of the best characteristics to have in a person.
Ahmad is highly recommended. I've never known someone to create such useful things on a regular basis.
Truly impressive sir. You just pump stuff out. It's incredible. I've read over Ahmad's tutorial a few times and implemented most of it. He's the bee's knees for this kind of stuff.
— In ref to the WordPress & Gulp implementation via WPGulp. This is a gorgeous, high contrast theme that stands out without getting in the way.
Especially great for doing developer talks and screencasts and maintained by a supremely dedicated expert in all the VSCode pro tips.
Yes, Ahmad writes great WordPress tutorials and makes great looking themes and websites, but that's not the only reason I endorse Ahmad.
Ahmad is a great community member, he is a core contributor to WordPress and always helpful to other WordPress users.
Also, he is a really nice guy, which is important.
Ahmad has written tutorials for me to publish at Tuts+ on a number of occasions, and I always appreciate his level of expertise both in the subject matter…, and in helping to educate others.
I would hire Ahmad again for… training or consultancy in a heartbeat.
I highly recommend Ahmad.
It is extremely rare that you come across highly skilled talent like Ahmad!
We worked together on several occasions over the years and his efficiency is beyond superior.
The comments, and markdown syntax semi-hidden state styling is also a good idea! If it's not critical to always see this information then it makes sense to reduce it's visibility.
I jumped ship from Cobalt 2 by Wes to 🦄 Shades of Purple theme by Ahmad Awais and I'm not looking back, beautiful shades of purple lighten up my code in a way that no other theme can, great job Ahmad!
3. The CLI as a tool for Node.js
At go6.media we always use Shades of Purple for all our PHP/HTML/JS/CSS and other languages. It's so beautiful and easy to read, we also added some slight tweaks to make it even better and we could not be happier that we found it.
Ahmad takes his extension seriously and fixed a bug for me overnight. A fantastic theme that is both attractive but more importantly, effective in bring your attention to the import parts of your code.
I started loving the 🦄 Shades of Purple theme from its name ;) After seeing images of the themes, I saw there was more and to get to know about the 'more', an installation will have to occur which did occur..After installation, I got to find out that the theme is super duper awesome than I thought… Welldone Ahmad Awais.
Just installed 🦄 Shades of Purple and absolutely love it!
Thank you for creating it! I love these colors!
I also switched from Cobalt2. And just beginning a new job as a React.js dev, with it :-).
I started using SOP during the better release and ever since it has being a perfect choice for me.
Love to see my IDE always with the shades of purple splash.
Have been using 🦄 Shades of Purple theme for the last couple of weeks and in love with it.
Its fun writing code with those shades of purple <3.
To dig deeper into Redis, you can visit this tutorial.
2. Install Node.js
Let’s learn how to deploy our Node application. I deploy all my projects on DigitalOcean. I highly recommend it to developers. If you have never tried DigitalOcean, give it a shot with a $10 discount for the first month.
Click here to go to the DigitalOcean droplet creation screen.
Choose a $5 plan and create the droplet. After creating a droplet wait for some time, DigitalOcean will send you an email containing the credentials. Login to your droplet using the following command.
Provide the password given in the email and you are good to go.
Once you are logged in, update the system using the following command.
Install the latest Node on your Server.
sudo apt-get install -y nodejs
Install the PM2 process manager.
Our server is ready to host our Node applications.
Github is a code hosting platform. Learn how to host your code in the Github platform.
Let’s push our code to Github. Go to Github.com and create a new repository.
Copy the repository path. Assuming you have Git installed in your machine. Switch to the project directory and execute these commands one by one.
git add .
git commit - m "first push"
git remote add origin << github repo URL >>
git push origin master
Login to your server using SSH.
Clone the Github project.
Switch to the project directory.
Run the Node project using PM2.
PM2 is a process management tool for Node. Using PM2 we can ensure 99% uptime of your application.
Test your application using Droplet IP and port on which your application is running.
Awesome. You have successfully developed and deployed your application. Here is another article related to deployment of application in the production server.
7. Environment variables in Node.js
I have created a PDF format of this Node js tutorial for beginners. You can visit this page to download the book.
Learn Node.js from scratch
We have written a lot of Node js tutorials on different topics, listing some of the best articles for you to read it further.
Building Email Verification System Using Node and Redis
Microservices Architecture with Node.js
Load Balancing Node.js Application Servers with Nginx
Building a URL Shortener with Node.Js and Redis
Load Balancing Node.js Application Servers with Nginx