Latest update: 18.11.2018

In addition to built-in and custom Node.js modules, there is a huge layer of various libraries and frameworks, various utilities that are created by third-party manufacturers and which can also be used in the project, for example, express, grunt, gulp and so on. And they are also available to us within Node.js. To make it more convenient to work with all third-party solutions, they are distributed in the form of packages. A package essentially represents a set of functionality.

To automate the installation and updating of packages, a package management system or managers are usually used. Directly in Node.js, the package manager NPM (Node Package Manager) is used for this purpose. NPM is installed by default with Node.js, so there is no need to install anything additional. But you can update installed version until the very last. To do this, run the following command in the command line/terminal:

Npm install npm@latest -g

To find out the current version of npm, enter the following command in the command line/terminal:

For us, the npm manager is important in the sense that it makes it easy to manage packages. For example, let's create on the hard drive new folder modulesapp (In my case, the folder will be located at C:\node\modulesapp ).

Next, as an example, we will install express in the project. Express introduces a lightweight web framework to make working with Node.js easier. In this case, we will not consider the Express framework in detail for now, since this is a separate large topic. And we use it only to understand how third-party modules are installed in the project.

To install the Express functionality into a project, first navigate to the project folder using the cd command. Then we enter the command

Npm install express

After installing express, a node_modules subfolder will appear in the modulesapp project folder, which will store all installed external modules. In particular, the node_modules/express subdirectory will contain the Express framework files.

// get the Express module const express = require("express"); // create an application const app = express(); // install a handler for the "/" route app.get("/", function(request, response)( response.end("Hello from Express!"); )); // start listening for connections on port 3000 app.listen(3000);

The first line gets the installed express module, and the second creates an application object.

In Express, we can associate request processing with specific routes. For example, "/" - represents home page or root route. The app.get() function is called to process the request. The first parameter of the function is the route, and the second is the function that will process the request along this route.

And for the server to start listening for connections, you need to call the app.listen() method, which is passed the port number.

Let's start the server with the node app.js command:

And in the address bar of the browser, enter the address http://localhost:3000/:

package.json file

To more conveniently manage application configuration and packages, npm uses the package.json configuration file. So, let's add modulesapp to the project folder new file package.json:

("name": "modulesapp", "version": "1.0.0" )

Only two sections are defined here: the project name is modulesapp and its version is 1.0.0. This is the minimum required package.json file definition. This file may include many more sections. More details can be found in the documentation.

Now let's add express again using the following command:

Npm install express --save

The --save flag specifies that information about the added package should be added to the package.json file.

And after executing the command, if we open the package.json file, then we will see the package information:

("name": "modulesapp", "version": "1.0.0", "dependencies": ("express": "^4.14.0") )

Information about all added packages that are used when the application starts is added to the dependencies section.

The package.json file plays a big role and can make development easier in a variety of situations. For example, when hosting in different repositories, we are often limited by the allocated disk space, while the node_modules folder with all the downloaded packages can take up quite a decent amount of space. In this case, it is more convenient to place the main project code without node_modules. In this case, we can define all the packages in the package.json file and then run the command to download all the packages

This command will take the definition of all packages from the dependencies sections and load them into the project.

devDependencies

In addition to the packages that are used in the application when it is running, for example, express, that is, in the "production" state, there are also packages that are used when developing the application and testing it. Such packages are added to another section - devDependencies. In the above example it is not defined, but if we added some grunt or gulp, they would be in the devDependencies section.

For example, let's load the jasmine-node package into the project, which is used to test the application:

Npm install jasmine-node --save-dev

The --save-dev flag specifies that the package information should be saved in the devDependencies section of the package.json file:

( "name": "modulesapp", "version": "1.0.0", "dependencies": ( "express": "^4.14.0"), "devDependencies": ( "jasmine-node": "^1.14 .5" ) )

Removing packages

To remove packages, use the npm uninstall command. For example:

Npm uninstall express

This command removes the package from the node_modules folder, while at the same time information about this package remains in the package.json file. To remove information from package.json as well, use the --save flag:

Npm uninstall express --save

Semantic versioning

Semantic versioning is used to determine the package version. The version number is usually specified in the following format: "major.minor.patch". If a bug is found in an application or package and it is fixed, the “patch” number increases by one. If some new functionality is added to a package that is compatible with a previous version of the package, then this is a small change and the "minor" number increases. If some major changes are made to the package that are incompatible with the previous version, then the “major” number increases. That is, looking at different versions packages, we can guess how big the differences are.

In the express example, the package version also contained an additional caret character: "^4.14.0". This symbol means that when installing a package into a project using the npm install command, the latest available version from 4.14.0 will be installed. In fact, this will be the last available version between 4.14.0 and 5.0.0 (>=4.14.0 and<5.0.0). Более подробно про сематическое версионирование в npm можно посмотреть .

npm commands

NPM allows you to define commands in your package.json file that perform specific actions. For example, let's define the following app.js file:

Let name = process.argv; let age = process.argv; console.log("name: " + name); console.log("age: " + age);

In this case, we receive the parameters passed to the application when the application was launched.

And define the following package.json file:

( "name": "modulesapp", "version": "1.0.0", "scripts": ( "start": "node app.js", "dev": "node app.js Tom 26") )

A scripts section has been added here, which defines two commands. In general, there can be many teams in accordance with the goals and objectives of the developer.

The first command is called start . It essentially runs a node app.js command, which executes the code in the app.js file

The second command is called dev. It also executes the same file, but also passes two parameters to it.

Team names can be arbitrary. But here one point must be taken into account. There are, relatively speaking, reserved names for commands, for example, start , test , run and a number of others. There aren't very many of them. And just the first command from the above defined package.json file is called start. And to execute similar commands in the terminal/command line, you need to run the command

Npm [command name]

For example, to run the start command

Npm start

Commands with other names, such as "dev" in the above file, are run like this:

Npm run [command_name]

For example, let's execute both commands sequentially.

  • Translation

npm is the node.js package manager. It can be used to manage modules and dependencies.
A little cheat sheet of all my favorite npm commands:

npm installation

npm update

There are several ways to update npm. I prefer:
curl https://npmjs.org/install.sh | sh
or
npm install npm -g

Find packages in npm

npm search hook.io
Hint: You can also use search.npmjs.org
Second tip: To search, you need to know the name of the required package (everything is fine searching for any word both in the package name and in its description, maybe I translated it incorrectly?)

View package information

npm view hook.io

Local installation of packages

For demonstration, let's take the http-server package.
http-server is a package we"ve written which provides an easy to use wrapper around node"s core http.Server class. This module makes for a good example, since it's API provides both a CLI binary and a requirable node.js module.
http-server - The package we wrote provides an easier interface to use the base http.Server module from node.js. This module is a good example of API usage for both the binary CLI and the node.js plugin.
npm install http-server
So we will install http-server in our working directory.
You will see a new folder in node_modules. You can ignore this now.

Installing the package in our application

mkdir mynewapp/ cd mynewapp npm install http-server touch test.js
test.js
var HTTPServer = require("http-server"); var httpServer = new HTTPServer(( root: "./public" )); httpServer.start();
let's run the script
node test.js
Notice how we do: require("http-server")? What kind of magic is this? (well done author)
http-server is not a core node.js module. We just installed this package from npm. Node.js and npm interact and automatically include our local modules from the node_modules directory.

Understanding the difference between global and local installation

By default, npm will install all packages in the local directory you are currently working in. This is right. This may seem a little confusing if you have worked with previous package management systems before.
For example: mkdir anotherapp/ cd anotherapp/ touch test.js
test.js
var HTTPServer = require("http-server");
now let's run our script
node test.js
we will get this error:
node.js:134 throw e; // process.nextTick error, or "error" event on first tick ^ Error: Cannot find module "http-server" at Function._resolveFilename (module.js:326:11) at Function._load (module.js:271: 25) at require (module.js:355:19) at Object. (/Users/maraksquires/dev/nodeapps/anotherapp/test.js:1:80) at Module._compile (module.js:411:26) at Object..js (module.js:417:10) at Module. load (module.js:343:31) at Function._load (module.js:302:12) at Array. (module.js:430:10) at EventEmitter._tickCallback (node.js:126:26)
This is quite logical, we installed http-server locally in "/mynewapp/", and not in "/anotherapp/".
There are two solutions in this situation:
a) Install the package again, but locally in our new application
cd anotherapp/ npm install http-server
b) Install the package globally
npm install http-server -g

Global package installation

If you want the package to be available to all applications, you need to install it globally:
npm install http-server -g
The -g flag means that http-server should be installed globally and be available to all applications.
Now we can call it require("http-server") in any of our applications.

In addition, since the http-server package has its own executable file, this file will also be installed as the http-server executable and available in commands.
Now you can simply run the command:
http-server

Removing a locally installed package

npm uninstall http-server

Removing a globally installed package

npm uninstall http-server -g

Installing a specific package version

npm install [email protected]

Installing a module from Github

Important. In some cases, there will be patches, forks, or branches that you want to use that have not yet been published to npm. Fortunately, the source code for most npm modules is also available at www.github.com
git clone git://github.com/nodeapps/http-server.git cd http-server/ npm link
Now our cloned version of http-server is linked locally.

Link any packages locally

If you have a separate directory containing an npm package, you can create a local link for it. This is useful in situations where we don't want to publish our package to the npm repository.
cd http-server/ npm link
Our local version of http-server is created "linked" for our local machine. (the connection is created as “copy-paste”, first you need to go to the desired directory and do “copy”, then go to the desired directory and do “paste”. So now we have learned how to do “copy”, and below we will talk about “ paste" of this module)

Local package associations for multiple applications

As we saw earlier, npm installs packages in the local directory by default. So npm link(link) works almost the same way.
mkdir newapp/ cd newapp/ npm link http-server
We indicate that we have now created a connection from http-server to our new newapp. If we had not run npm link http-server, we would have received a missing module error. (and here is our “paste”, which I wrote about above, now you should understand the logic of creating connections)

Unlinking Application Packages

cd newapp/ npm unlink http-server
(here we are simply undoing our "paste" for this application)

In this guide I will tell you how to install webpack, its dependencies and set up merging and minifying scripts through it.
This is the first part of the series "Webpack in a NetBeans project".

1. Why is all this needed:

1. Several times in projects I needed to combine several scripts into one. The reason for this division is that each script performs its own task, and in order to reduce http requests when releasing a plugin (or an addition to the WordPress plugin WP-Recall), everything needs to be combined into one. I don't want to do this by hand.

2. I like to comment js (not maniacally, but to help myself - when I return to it after a long time), and comments in js are not comments in php - in the script they become a dead weight in the file and increase its size. And this file is loaded in the front.

3. Someone doesn’t want js to be read by humans. Well, you never know... "Obfuscation" comes to the rescue (from the Latin obfuscare - to obscure, darken; and English obfuscate - to make unobvious, confusing, confusing) - bringing the source text or executable code of a program to a form that preserves its functionality , but makes it difficult to analyze, understand operating algorithms and modify during decompilation.

Ideal solution:

You write scripts in different files;
You comment on them “from the heart”;
Don't skimp on the names of the variables (they should be meaningful).

On release:

You combine automatically specified files into one;
Minimization occurs automatically (removing spaces, hyphens and comments) - the script goes on one line;
The file is automatically obfuscated - variable names are abbreviated.

All this leads to a reduction in file weight. Which ultimately affects faster file loading.

Look at the example (all screenshots are clickable):
Result of file weight ~2 times

Well, the time to “grow further” has come. The choice fell on webpack. But in order to install it, you will have to install the Cygwin terminal in NetBeans (hereinafter: netbeans, ide), install node.js with npm (node ​​package manager) inside, and then just install the webpack itself.
The adventure will not end here - in the process of running the command $ npm run build you will have to deliver webpack-command and webpack-cli - because A message will appear in the terminal that they are not there. It will be impossible to move further without these packages.

2. Global settings and settings:

I have never worked through the terminal or command line in my life. I kept pushing buttons. But it won’t work like that here.

2.1. Install Cygwin terminal:

ide NetBeans has the ability to work through the terminal.
We open any of our projects and here it is located:
"Tools" -> "Open in terminal"

Let's open the terminal

When you open a terminal, ide will ask you to install it. You will see a message like this:

install Cygwin and restart ide

Cygwin is a set of utilities for running Windows via Unix commands. The package also contains a terminal.

I’m interested in solving a couple of more questions on this topic:
Minifying and merging css via webpack;
Autoprefixes based on caniuse service;
And of course, jsx compilation via babel.

All of course through netbins. Therefore, we will consider this lesson the first in a series.

p.s. If you notice an inaccuracy or typo, have questions or want to comment on the current article, welcome to comment.

If you work with webpack, but in a different ide, share your impressions in the comments. If you don’t use it yet, but are looking closely, also write with which ide you will set up close work.

There is ample documentation that covers the question "Why Node?" But what really matters to me is not where Node is today, but where it will be tomorrow. Without a doubt, the Rails community has brought a lot to the table, but all these great ideas are hard to swallow because they are locked inside Ruby. As amazing as Ruby is, not everyone wants to become a Ruby developer.

Depending on the installation process, npm may or may not be installed. To check, just run:

$ npm --version

If npm is not installed, do the following:

$ curl http://npmjs.org/install.sh | sh

npm is the package manager for Node, so you can't use a package manager to install a package manager.

Using npm

Now that npm is installed, all registered packages are just a command in the console. To install a basic package, run:

$ npm install<пакет>

This method will install the package into the node_modules folder relative to your project. Sometimes you will need to install libraries globally so that you can access them from any application's code without necessarily requiring them as a dependency.

To do this, you need to add the -g flag during the installation process:

$ npm install -g<пакет>

Depending on how Node.js is installed on your system, you may not have access to install the global package. To get around this, simply add the sudo command at the beginning:

$ sudo npm install -g<пакет>

Using npm with a project

The most common use case for npm is maintaining a dependency manifest for your project. All this is stored in the package.json file.

You can create this file yourself, although there are also methods to generate this file. In any folder, just run npm init and the console will take you through a series of questions, resulting in something like this:

( "name": "toss-this", "version": "0.0.0", "description": "", "main": "index.js", "scripts": ( "test": "echo\ "Error: no test specified\" && exit 1" ), "author": "", "license": "ISC" )

If your project already contains package.json, adding the package to it is very easy using npm install. Just include the --save flag in the command like this:

$ npm install<пакет>--save

Adding Grunt to the project will update package.json by adding the dependencies object to the file:

( "name": "toss-this", "version": "0.0.0", "description": "", "main": "index.js", "scripts": ( "test": "echo\ "Error: no test specified\" && exit 1"), "author": "", "license": "ISC", "dependencies": ( "grunt": "^0.4.5" ) )

In addition to this, if you want to specify a dependency for development only and not for the production project, then pass the -dev flag:

$ npm install<пакет>--save-dev

By adding Gulp as a development dependency, a devDependencies object appears in your package.json file:

( "name": "toss-this", "version": "0.0.0", "description": "", "main": "index.js", "scripts": ( "test": "echo\ "Error: no test specified\" && exit 1"), "author": "", "license": "ISC", "dependencies": ( "grunt": "^0.4.5"), "devDependencies": ("gulp": "^3.6.2" ) )

Learn more about npm

npm is a surprisingly complex utility when it comes to package management. See this npm cheat sheet for more details.

Learn more about package.json

package.json contains many features. To find out more about how it all works, visit

JavaScript is an integral part of web development. Front-end developers use JavaScript to improve the user interface, add interactivity, AJAX data transfer, etc.

In fact, with sufficient knowledge of JavaScript, you can work with "full stack" web applications. The key to this is Node.js, which makes it possible to run JavaScript on the server side.

Node.js is also used in desktop application development and application deployment tools that make web application simpler. For example, by installing Node.js on your computer, you can quickly convert CoffeeScript to JavaScript, SASS to CSS, and reduce the size of your HTML, JavaScript, and graphics files.

In addition to Node.js installed, you will also need NPM, which is designed to install and manage Node.js modules. With NPM you can add many new and useful tools to your project much easier.

How to work with Node.js

Node.js is not a program that you simply launch by clicking on an icon; you will not find it in the taskbar or in the application list. To use Node.js you need to run commands (instructions) in the console (command line), so be prepared for this.

Installing Node.js

Installing Node.js and NPM is quite simple, everything is done using an installation package that can be downloaded from the Node.js website: .

1. Download the installer for Windows from the official website

2. Run the installer

3. Follow the instructions in the installer

4. Reboot your computer for Node.js to work correctly

Checking the correct installation of Node.js and NPM

To make sure everything is installed successfully, you need to run simple commands.

Checking Node.js

To check Node.js you need to open the command line (console (Win + R and enter cmd)) and run the command:

The command will return the current version of node.js

Checking NPM

In order to check whether NPM is installed, you need to run the command on the command line (console):

The command will return the current NPM version

Let's try how node.js works with a file

For example, create a test.js file with the following content:

Console.log("Node is installed!");

And in the command line (console) run the following command:

Node test.js

How to update Node.js and NPM

To install new versions of Node.js and NPM, simply download the latest version of the package from the official website and run it.

How to remove Node.js and NPM

Node.js and NPM are uninstalled just like most programs in Windows. Those. Control Panel => Uninstall a program, select Node.js, right-click and select Uninstall.

Node.js packages

Also on the NPM website () all official Node.js packages are listed.


Close