Что такое node js server side javascript
Перейти к содержимому

Что такое node js server side javascript

  • автор:

Node.js Server-Side JavaScript – What is Node Used For?

Ihechikara Vincent Abba

Ihechikara Vincent Abba

Node.js Server-Side JavaScript – What is Node Used For?

The release of Node.js in 2009 by Ryan Dahl increased the scope of what developers could do with JavaScript. Prior to that, you could only use JavaScript on the client side (the browser) or frontend of web applications.

With Node.js, developers can create server side applications, command line tools, and more.

This article is not a crash course on how to use Node.js (you’ll find resources for that in the last section of this article). Rather, it’s an introduction to what Node.js is, its features, and what it is used for.

What is Node.js?

Node.js is an open source JavaScript runtime environment that lets developers run JavaScript code on the server.

If that’s too complex for you to understand then you should think of it this way: Node.js is JavaScript that runs outside the browser — on the server.

Note that Node.js is not a programming language — it’s a tool.

What Is So Special About Node.js?

In this section, we’ll discuss some of the features that make Node.js cool to use.

The aim is not to compare Node.js to other backend technologies, but to help you understand some of its functionalities.

Single Threaded and Asynchronous

Node.js is fast at executing tasks (receiving requests and sending back responses) because of its single threaded and asynchronous nature.

Let’s explain some of the terms above.

By single threaded, this means that Node.js has a single source for handling requests. Multiple threaded backend technologies allocate a new thread for every new request.

You can think of a thread as someone who renders a service to multiple people. A very popular real life example would be a restaurant. We’ll explain this example further along with the asynchronous part of Node.js.

Node.js is asynchronous because it can handle multiple requests simultaneously. Let’s get back to the restaurant example.

A customer gets to a restaurant and sits down waiting for a server. The server gets to the customer’s table and takes their order. The order is then taken to the kitchen.

But the server doesn’t wait for the order to be ready before proceeding to the next customer. They’ll return with what the customer ordered for when its ready – in the meantime, the server proceeds to the next customer and repeats the same process.

The example above is similar to how Node.js works under the hood. It is able to process multiple requests using a single thread asynchronously (without waiting for one request’s completion before moving to the next).

So when the response for a request is ready, it is sent back to the client.

The single threaded and asynchronous nature of Node.js makes it very fast and ideal for building data-intensive and real-time applications.

JavaScript Everywhere

Another advantage of using Node.js as a web developer is the possibility of using JavaScript on the frontend and backend of your web app.

Before the release of Node.js, web developers had to learn a different programming language to build the backend of their web apps.

Of course, some developers still use different languages for their backend but Node.js makes it easy to use just one language — JavaScript – if you want.

Fast Execution Time

Node.js is built on Google’s V8 JavaScript engine which has a very high performance. This lets Node execute requests quickly.

Cross Platform Compatibility

Node.js supports many major platforms. So you can write your code and it will run on Windows, MacOS, LINUX, UNIX and even some mobile devices.

What is Node Used For?

Here are some of the cool things you can do with Node.js:

  • Create HTTP web servers.
  • Generate web pages dynamically.
  • Collect and send form data to a database.
  • Create, read, update, and delete data stored in a database.
  • Create APIs.
  • Build command line tools.
  • Read, write, move, delete, and open/close files on a server.

Summary

In this article, we talked about Node.js. We first had a look at what it really is.

We then talked about some the features that make Node.js stand out.

Lastly, we saw a list of how you can use Node.js.

How to Learn Node.js

Now that you’ve had a brief introduction to what Node.js is, its features, and what it is used for, here are some resources that you can use to learn how to use Node.js:

  • freeCodeCamp’s Back End Development and APIs certification. You’ll learn how to write back end apps with Node.js and npm. You’ll also build web applications with the Express framework, along with MongoDB and the Mongoose library.
  • An 8-hour course on the freeCodeCamp.org YouTube channel that’ll teach you Node.js and Express.
  • A 10-hour project based course on the freeCodeCamp.org YouTube channel. You’ll build four projects from the knowledge gained from the 8-hour course above.

What is the difference between Node.js and server-side JavaScript?

In this tutorial, we will explore the differences between Node.js and server-side JavaScript. By the end of this tutorial, you will have a clear understanding of what sets them apart and how they work in different contexts. Let’s dive in!

Introduction to Node.js

Node.js is an open-source, cross-platform runtime environment built on Chrome’s V8 JavaScript engine, which allows developers to execute JavaScript code on the server-side. It was created by Ryan Dahl in 2009 to address the limitations of traditional web servers and to provide a more efficient way of handling concurrent connections. Node.js uses an event-driven, non-blocking I/O model, making it lightweight and efficient.

Introduction to Server-side JavaScript

Server-side JavaScript refers to any JavaScript code that runs on the server rather than the client (browser). Before the advent of Node.js, server-side JavaScript was executed using different server-side engines like Rhino (Mozilla) or JScript (Microsoft). These engines allowed developers to create server-side web applications using JavaScript, but they lacked the performance and flexibility provided by Node.js.

Code Snippet: A simple «Hello World» server using Node.js

 const http = require('http'); const server = http.createServer((req, res) => < res.writeHead(200, < 'Content-Type': 'text/plain' >); res.end('Hello World\n'); >); server.listen(3000, () => < console.log('Server running at http://localhost:3000/'); >); 

Differences between Node.js and Server-side JavaScript

1. Runtime Environment

Node.js provides a runtime environment for executing JavaScript on the server-side, whereas server-side JavaScript (without Node.js) relies on different engines like Rhino or JScript. Node.js is built on Chrome’s V8 engine, ensuring high performance and efficiency.

2. Libraries and Modules

Node.js comes with a rich set of built-in libraries and a vast ecosystem of third-party modules available through the Node Package Manager (NPM). In contrast, traditional server-side JavaScript engines have limited built-in libraries and lack a comprehensive package management system like NPM.

3. Performance and Scalability

Node.js uses an event-driven, non-blocking I/O model, which allows it to handle a large number of concurrent connections efficiently. This makes it an excellent choice for building scalable applications. Traditional server-side JavaScript engines do not provide the same level of performance and scalability as Node.js.

4. Community and Ecosystem

Node.js has a large and active community of developers who contribute to its development and create third-party modules. This vibrant ecosystem makes it easier for developers to find solutions to common problems and integrate new features. Traditional server-side JavaScript engines have a smaller community, which can limit the availability of resources and support for developers.

Conclusion

In conclusion, Node.js and server-side JavaScript both enable developers to write JavaScript code that runs on the server. However, Node.js provides a more advanced and efficient runtime environment, a rich set of built-in libraries, a vast ecosystem of third-party modules, and a large, active community. This makes Node.js a better choice for modern web development, especially when building scalable and high-performance applications.

What is Node.js? Server-Side JavaScript Development Basics

David Clinton

David Clinton

What is Node.js? Server-Side JavaScript Development Basics

Node.js is a powerful runtime environment for executing JavaScript code outside of a web browser. It brings the JavaScript language to the server-side, enabling developers to build scalable, high-performance, and event-driven applications.

Let’s discover how Node.js code works, and how that code can be integrated within your JavaScript and then executed.

This article comes from my Complete LPI Web Development Essentials Study Guide course. If you’d like, you can follow the video version here:

Node.js allows developers to use JavaScript both on the client-side and the server-side, providing a unified language and ecosystem. This eliminates the need for context switching and enables code reuse between the front-end and back-end. This results in improved productivity and reduced development time.

Node.js has a vast and active ecosystem of modules and libraries available through the Node Package Manager (npm). This rich ecosystem offers ready-to-use tools and packages for various functionalities, such as web frameworks, database connectors, authentication, and testing frameworks.

Developers can leverage these modules to accelerate development and enhance application functionality.

Given all that, Node.js is particularly well-suited for building:

  • Web applications
  • Scalable APIs
  • Real-time applications requiring instant data updates and bidirectional communication like chat applications and multiplayer games
  • Streaming applications like audio or video processing or real-time analytics
  • Single-page applications
  • Internet of Things deployments

All that sound like a good match for some useful web applications? I thought it would. So let’s see how it all works.

How to Build a Node.js Server Environment

First off, you won’t need to set up and run a third-party web server like Apache HTTPD or NGINX or place your content within the /var/www/html directory hierarchy. That’s because Node.js is, among other things, a web server framework.

Let me show you what that means. You’ll need to make sure you’ve got Node.js installed along with the necessary dependencies. By and large, you’ll use the NPM package manager to get that done. There’s excellent documentation for installing Node on your OS from the official website.

You can confirm that both Node and NPM are live and waiting for action by running these commands:

$ node -v v18.16.0 $ npm -v 9.5.1

Just to have some HTML to work with, you should find or create a simple index.html file and save it to a local directory on your machine. This command will download the html of an LPI page from my own website if you need something quick and small:

wget https://bootstrap-it.com/lpi/

Let’s take a look at the server.js code we used for our Node server.

const http = require('http'); const fs = require('fs'); const server = http.createServer((req, res) => < // Read the HTML file fs.readFile('index.html', 'utf8', (err, data) =>< if (err) < res.writeHead(500, < 'Content-Type': 'text/plain' >); res.end('Error loading HTML file'); return; > res.writeHead(200, < 'Content-Type': 'text/html' >); res.end(data); >); >); const port = 3000; server.listen(port, () => < console.log(`Server is running on http://localhost:$`); >);

Now let’s work through that code, one section at a time. We begin by loading two necessary modules: http to manage the website hosting, and fs to read the HTML files.

const http = require('http'); const fs = require('fs');

We then create a server function – called server . When called, it will either read and serve our index.html file (generating a 200 success code) or, if there’s a problem reading the file, it’ll generate a 500 error message.

 fs.readFile('index.html', 'utf8', (err, data) => < if (err) < res.writeHead(500, < 'Content-Type': 'text/plain' >); res.end('Error loading HTML file'); return; >

The code continues by setting 3000 as the listening port for our application – although, technically, you could change that to any value you like between 1 and 65535.

const port = 3000;

Finally, we call the server function using the listen method and specifying the port number, and then writing an entry to console.log .

server.listen(port, () => < console.log(`Server is running on http://localhost:$`);

How to Execute Your Node.js Server

Running the npm init command in the same directory were your program files will live is used to initialize a new Node.js project and create a package.json file.

The package.json file serves as the manifest for the project, containing metadata and configuration information about the project, its dependencies, scripts, and other details.

You can manually add dependencies to the file or use:

npm install

. to add packages and their versions to the dependencies section of the package.json .

When you actually run npm init to initialize a directory for a new project, a script will ask you some questions. The default values npm suggests for you will include 1.0.0 as a version number and an entry point of index.js .

You'll also have the option of setting a git repo, keywords, and a choice of user license models. All the defaults should work just fine.

When that's done, the script will show you the proposed JSON-formatted version of your settings and ask for your approval. The package.json file that was created will reflect those settings.

For our project, install the MySQL database connector module along with express.js:

$ npm install mysql $ npm install express.js

Neither takes more than a few seconds. When that's all done, I'll see that there's now a new file in town: package-lock.json .

Peeking inside that file will show you an awful lot of JSON goodness. What's that all about? The package-lock.json file is automatically generated by npm when you install dependencies for your project. It serves as a lockfile that ensures deterministic and reproducible builds of your project across different environments.

It's important to include the package-lock.json file in version control systems like Git so that other developers or deployment environments can reproduce the exact dependency tree and versions used in the project. This ensures consistency and avoids potential conflicts or surprises when working with dependencies.

There will also be a new node_modules directory that was automatically created and populated by that init operation. This directory is a storage location for all the packages and modules our project relies on. When you install packages using npm install , the downloaded packages are placed here.

npm automatically resolves and installs the required dependencies of each package. It creates a hierarchical structure in the node_modules directory that reflects the dependency tree of your project.

Launching your server is straightforward:

$ node server.js

To view the service, open your browser and direct it to the application URL, using port 3000 . When your browser is on the same machine as the Node server, this is how that'll look:

localhost:3000

Of course, you don't really need Node.js just for that. The value of Node.js comes from building user interactivity by integrating it with a backend database. That can happen using Express.js, but it'll have to wait for another time.

Wrapping Up

What we have seen here is how the magic behind building a Node.js environment can provide all the infrastructure and backend functionality you need to launch and maintain an interactive and dynamic server.

Node.js Server-Side JavaScript — что это в диспетчере задач?

Node.js Server-Side JavaScript — компонент взаимодействия программ, может использоваться например в ПО Adobe для работы модулей/плагинов.

Простыми словами: так просто не ответить что это, почему? Node.js это библиотека, которая позволяет использовать возможности языка JavaScript на компьютере. При помощи этой библиотеке функционируют разные модули/плагины в разных программах. То есть у вас на ПК Node.js Server-Side JavaScript может быть например от Фотошопа или от другой программы.

Разбираемся

  1. Если очень образно говоря, то Node.js это компонент, позволяющий использовать приложения на компьютере, который были написаны на языке JavaScript, который в принципе создан не для ПК, а для веб-приложений. На JavaScript пишут код (функции) для веб-сайтов, но не для компьютеров. А вот чтобы использовать на ПК возможности JavaScript — был придуман компонент Node.js. Но суть не в этом.
  2. Node.js Server-Side JavaScript может появиться после установки популярного софта, например от Адобе. Этот процесс позволяет обмениваться данными между программами (ПО Адобе содержит множество дочерних модулей). Также Node.js может использоваться для написания плагинов/дополнений.
  3. Также этот компонент может устанавливать соединение с интернетом. Зачем? Непонятно. Но важно понимать, что компонент может требоваться для работы некоторых модулей ПО, среди которых могут быть и модули проверки лицензии. Поэтому если заблокировать доступ в интернет — могут быть проблемы из-за невозможности проверить лицензию. Еще вместо лицензии может проверять наличие новой версии ПО.

Нашел комментарий как избавиться от процесса, однако предупреждаю — если будете делать, то только на свой страх и риск:

Что можно еще попробовать сделать? Можно попробовать радикально запретить работу процесса:

  1. Найдите Node.js Server-Side JavaScript в диспетчере задач.
  2. Нажмите правой кнопкой и выберите пункт Открыть расположение.
  3. Откроется папка с выделенным файлом. Процесс в диспетчере завершаем.
  4. Переименовываем файл, можно просто добавить символ нижнего пробела _. Если при переименовании будет ошибка — попробуйте утилиту Unlocker (умеет переименовывать/удалять заблокированные папки/файлы).

Однако этот способ может привести к ошибкам ПО, где используется компонент. Node.js может использоваться не только софтом Адобе, но и другим.

Но в целом, если в диспетчере такая картина:

И при этом доступ в интернет для Node.js Server-Side JavaScript не заблокирован — это НЕнормальное явление. Если у вас ПО лицензированное — нужно написать в техподдержку. Если качали ПО с торрентов, то такое ПО спокойно может быть глючным. Лучше конечно переустановить, скачав с официального сайта.

Надеюсь данная информация оказалась полезной. Удачи и добра, до новых встреч друзья!

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *