How to use npm

How to use npm

npm для простых смертных

How to use npm. Смотреть фото How to use npm. Смотреть картинку How to use npm. Картинка про How to use npm. Фото How to use npm

Эта статья предназначена для тех, кто не очень дружит с Node.js, но хочет использовать приложения вроде Grunt, Gulp и тому подобные. Процесс работы с этими приложениями подразумевает редактирование файла package.json и использование команд npm, так что понимание принципов работы npm поможет вам справиться с трудностями.

Node.js за 5 минут

Понимание того, что такое Node.js поможет вам лучше разобраться с npm. В двух словах — Node.js это интерпретатор языка JavaScript. Сам по себе Node.js является приложением, которое получает на входе и выполняет его.
Давайте создадим простую программу. Создайте файл helloworld.js и поместите в него следующий код:

How to use npm. Смотреть фото How to use npm. Смотреть картинку How to use npm. Картинка про How to use npm. Фото How to use npm

Программа просто выведет строку «Hello World» в терминал.

Пакеты в Node.js

Файл package.json

Файл package.json содержит в себе информацию о вашем приложении: название, версия, зависимости и тому подобное. Любая директория, в которой есть этот файл, интерпретируется как Node., даже если вы не собираетесь публиковать его.
Способ использования файла package.json зависит от того, собираетесь ли вы скачивать пакет или публиковать его.

Скачивание пакетов

Если вы хотите скачать пакет вручную, вам необязательно использовать для этого package.json. Вы можете выполнить в терминале команду npm с названием нужного пакета в качестве аргумента команды, и пакет будет автоматически скачан в текущую директорию. Например:

Также для скачивания пакетов вы можете использовать package.json. Создайте в директории вашего проекта файл package.json, и добавьте в него следующий код (мы не указываем название нашего пакета и версию, мы не собираемся его публиковать; мы указываем название и версию пакетов для загрузки):

Публикация пакета

Чтобы опубликовать пакет, вам потребуется собрать все исходные коды и файл package.json в одной директории. В package.json должны быть указаны название, версия и зависимости пакета. Например:

Использование пакета в качестве исполняемого файла

Теперь вы знаете, что такое пакет и как он может зависеть от других пакетов. Также вы узнали, как npm работает с пакетами. Давайте перейдём от теории к практике и установим Grunt.

Установка Grunt с помощью npm

Node.js and npm Tutorial: Installation and Usage

In order to use almost any development tools based in JavaScript, you’ll need to know how to use npm and Node.js. Gulp, Grunt, and Webpack are a few examples of popular technologies you may have heard of that require a knowledge of the Node ecosystem.

I find myself writing about this over and over again in the prerequisites of an article I’ve begun to write. I’d prefer to write one definitive guide to refer to in the future, so here it is.

JavaScript is a client-side programming language, which means it’s processed in the browser. With the advent of Node.js, JavaScript can also be used as a server-side language.

npm doesn’t stand for Node Package Manager*, which means it’s the tool to connect to the repository containing all the Node.js programs, plugins, modules and so on.

*npm actually does not stand for «Node Package Manager» but essentially that’s what it is and does, so most people refer to it that way.

Local vs. Global

This is the most confusing concept to understand at first, so it’s important to let this settle in. Traditionally, you’re used to globally installing any sort of program or software on your computer. If you want Spotify, you’ll download Spotify, and then it will be available to you.

With npm, you will have some global installs, but mostly everything will be done on a local project basis, meaning you’ll have to install everything you need for each project in its own directory. If you want to have a project running Gulp and Sass, you’ll create a directory, with a new npm install.

Installation on Windows

Installing everything on Windows is a breeze.

Install Node.js and npm

Node.js and npm can be installed from a download link. Go to the Node installation page, and download the Node installer. I have a 64-bit Windows 10 OS, so I chose that one.

Installation on a Mac or Linux

In order to install everything on a Mac, we’ll be running commands in Terminal.app, and Linux distributions vary.

Install Node.js and npm

We’re going to use Node Version Manager (nvm) to install Node.js and npm.

/.bash_profile file, and make sure source

/.bashrc is written in there somewhere. Restart the terminal.

Run the install command.

Run the use command.

Create a Project

At this point, you’re set to start setting up Gulp, Webpack, Browserify, or whatever your aim is. We can also create a simple project to test that everything is working properly.

Now initalize a new project with npm.

The following will pop up in the terminal, and prompt you for a few

First, it will ask for a package name.

The rest you can just press enter and skip. Now you’ll notice we have a package.json file that contains all the information we entered.

A package.json is a file that contains metadata about the project, and handles the dependencies (additional software and modules) of the project.

For example, writing this:

Will output this:

left-pad is a package on npm, which as we stated previously contains the registry for all publicly available packages.

As long as you ran this command inside the project directory, it will successfully install the dependency by creating a node_modules directory. It will also create a package-lock.json file, which we can ignore. Finally, it updated our package.json file with a new line.

Now the project recognizes the left-pad dependency as existing

Run Node in the terminal

Let’s create index.js in the root of our directory. This is everything you should have now:

For future reference, don’t bother looking in the node_modules rabbit hole. It will get really overwhelming with bigger projects.

In order to use a dependency, we use require() and put it in a variable, like so:

This will be the entirety of our index.js file, in which we require left-pad, run a leftPad() function, and send it to the console.

Since Node.js is not recognized by the browser, we’ll be testing this in the console. In your shell, run the node command followed by the filename in the root of your project.

If everything went well, you should have printed Hello, World! to the console, with two spaces on the left.

In this tutorial, we learned the following:

If you got lost at any point, view the source on GitHub.

With this knowledge, you’re ready to start using Gulp, Grunt, Webpack, Browserify, or anything else that depends on Node.js or npm.

Comments

About me

How to use npm. Смотреть фото How to use npm. Смотреть картинку How to use npm. Картинка про How to use npm. Фото How to use npm

Hello and thanks for visiting! My name is Tania Rascia, and this is my website and digital garden. 🌱

I’m a software developer who writes articles and tutorials about things that interest me. This site is and has always been free of ads, trackers, social media, affiliates, and sponsored posts.

I hope you enjoy the post and have a nice day.

The NodeSource Blog

You have reached the beginning of time!

All Posts

How To

An Absolute Beginner’s Guide to Using npm

How to use npm. Смотреть фото How to use npm. Смотреть картинку How to use npm. Картинка про How to use npm. Фото How to use npmTierney Cyren

in How To on Feb 17 2017

Using npm effectively is a cornerstone of modern web development, no matter if it’s exclusively with Node.js, as a package manager or build tool for the front-end, or even as a piece of workflows in other languages and on other platforms.

As such, I’ve written up a basic and detailed guide for understanding npm, for those who are entirely new to Node.js, npm, and the surrounding ecosystem.

An Absolute Beginner’s Guide to package.json

As a general rule, any project that’s using Node.js will need to have a package.json file. What is a package.json file?

At its simplest, a package.json file can be described as a manifest of your project that includes the packages and applications it depends on, information about its unique source control, and specific metadata like the project’s name, description, and author.

Let’s break down the core parts of a typical package.json file:

Specific Metadata: name, version, description, license, and keywords

Here’s an example of how these fields would look in a package.json file:

A package.json file is always structured in the JSON format, which allows it to be easily read as metadata and parsed by machines.

Understanding and Managing Your Project’s Dependencies: dependencies and devDepenendcies in your package.json

The other majorly important aspect of a package.json is that it contains a collection of any given project’s dependencies. These dependencies are the modules that the project relies on to function properly.

The Essential npm Commands

When using npm, you’re most likely going to be using the command line tool for the majority of your interactions. As such, here’s a detailed rundown of the commands that you’ll encounter and need to use most frequently.

Using npm init to Initialize a Project

The npm init command is a step-by-step tool to scaffold out your project. It will prompt you for input for a few aspects of the project in the following order:

It’s worth noting that if you’re content with the suggestion that the npm init command provides next to the prompt, you can simply hit Return or Enter to accept the suggestion and move on to the next prompt.

Once you run through the npm init steps above, a package.json file will be generated and placed in the current directory. If you run it in a directory that’s not exclusively for your project, don’t worry! Generating a package.json doesn’t really do anything, other than create a package.json file. You can either move the package.json file to a directory that’s dedicated to your project, or you can create an entirely new one in such a directory.

How to use npm init :

That said, if you’re interested in setting that up, you can learn how to set these defaults in the eleventh tip of our npm tricks article.

Usage:

Install Modules with npm install

Installing modules from npm is one of the most basic things you should learn to do when getting started with npm. As you dive deeper, you’ll begin to learn some variations on installing modules, but here’s the very core of what you need to know to install a standalone module into the current directory:

In the above command, you’d replace with the name of the module you want to install. For example, if you want to install Express (the most used and most well known Node.js web framework), you could run the following command:

The above command will install the express module into /node_modules in the current directory. Whenever you install a module from npm, it will be installed into the node_modules folder.

In addition to triggering an install of a single module, you can actually trigger the installation of all modules that are listed as dependencies and devDependencies in the package.json in the current directory. To do so, you’ll simply need to run the command itself:

Once you run this, npm will begin the installation process of all of the current project’s dependencies.

Usage:

Install modules and save them to your package.json as a dependency

Usage:

Install Modules and Save Them to Your package.json as a Developer dependency

Usage:

Install Modules Globally on your System

The final, and most common, flag for npm install that you should are the flags to install a module globally on your system.

Note: One caveat with global modules is that, by default, npm will install them to a system directory, not a local one. With this as the default, you’ll need to authenticate as a privileged user on your system to install global modules.

As a best practice, you should change the default installation location from a system directory to a user directory. If you’d like to learn to do this, take a peek at the seventh tip in our npm tricks article!

Руководство по Node.js, часть 5: npm и npx

Сегодня, в пятой части перевода руководства по Node.js, мы завершим разбор возможностей npm, в частности, коснёмся таких вопросов, как выяснение установленных версий npm-пакетов, установка старых версий пакетов, обновление зависимостей, локальная и глобальная деинсталляция пакетов. Здесь же мы поговорим и об npx.

How to use npm. Смотреть фото How to use npm. Смотреть картинку How to use npm. Картинка про How to use npm. Фото How to use npm

Выяснение версий установленных npm-пакетов

Для того чтобы узнать версии всех установленных в папке проекта npm-пакетов, включая их зависимости, выполните следующую команду:

В результате, например, может получиться следующее:

То же самое можно узнать и просмотрев файл package-lock.json проекта, но древовидную структуру, которую выводит вышеописанная команда, удобнее просматривать.

Для того чтобы получить подобный список пакетов, установленных глобально, можно воспользоваться следующей командой:

Вывести только сведения о локальных пакетах верхнего уровня (то есть, тех, которые вы устанавливали самостоятельно и которые перечислены в package.json ) можно так:

В результате, если, например, устанавливали вы только пакет cowsay, выведено будет следующее:

Для того чтобы узнать версию конкретного пакета, воспользуйтесь следующей командой:

В результате её выполнения получится примерно следующее:

Эта команда подходит и для выяснения версий зависимостей установленных вами пакетов. При этом в качестве имени пакета, передаваемого ей, выступает имя пакета-зависимости, а вывод команды будет выглядеть следующим образом:

Запись о пакете-зависимости в этой структуре будет выделена.

Если вы хотите узнать о том, каков номер самой свежей версии некоего пакета, доступного в npm-репозитории, вам понадобится команда следующего вида:

В ответ она выдаёт номер версии пакета:

Установка старых версий npm-пакетов

Установка старой версии npm-пакета может понадобиться для решения проблем совместимости. Установить нужную версию пакета из npm можно, воспользовавшись следующей конструкцией:

В случае с используемым нами в качестве примера пакетом cowsay, команда npm install cowsay установит его самую свежую версию (1.3.1 на момент написания этого материала). Если же надо установить его версию 1.2.0, воспользуемся такой командой:

Указывать версии можно и устанавливая глобальные пакеты:

Если вам понадобится узнать о том, какие версии некоего пакета имеются в npm, сделать это можно с помощью такой конструкции:

Вот пример результата её работы:

Обновление зависимостей проекта до их самых свежих версий

Кроме того, устанавливая некий пакет, npm находит и устанавливает его зависимости.

В package-lock.json так же будут внесены сведения об этом пакете. Вот его фрагмент:

Для того чтобы узнать, вышли ли новые версии используемых в проекте пакетов, можно воспользоваться следующей командой:

Вот результаты выполнения этой команды для проекта, зависимости которого давно не обновлялись:

How to use npm. Смотреть фото How to use npm. Смотреть картинку How to use npm. Картинка про How to use npm. Фото How to use npm

Анализ устаревших зависимостей проекта

Для того чтобы обновиться до новых мажорных версий всех используемых пакетов, глобально установите пакет npm-check-updates :

Затем запустите утилиту, предоставляемую им:

Локальная или глобальная деинсталляция пакетов

), выполните команду следующего вида:

При выполнении подобной команды текущая папка значения не имеет.

О выборе между глобальной и локальной установкой пакетов

Когда и почему пакеты лучше всего устанавливать глобально? Для того чтобы ответить на этот вопрос, вспомним о том, чем различаются локальная и глобальная установка пакетов:

.

Подключение локальных и глобальных пакетов в коде осуществляется одинаково:

Итак, какой же способ установки пакетов лучше всего использовать?

В общем случае, все пакеты следует устанавливать локально. Благодаря этому, даже если у вас имеются десятки Node.js-проектов, можно обеспечить, при необходимости, использование ими различных версий одних и тех же пакетов.

Обновление глобального пакета приводит к тому, что все проекты, в которых он применяется, будут использовать его новый релиз. Несложно понять, что это, в плане поддержки проектов, может привести к настоящему кошмару, так как новые релизы некоторых пакетов могут оказаться несовместимыми с их старыми версиями.

Если у каждого проекта имеется собственная локальная версия некоего пакета, даже при том, что подобное может показаться пустой тратой ресурсов, это — очень небольшая плата за возможность избежать негативных последствий, которые могут быть вызваны несовместимостью новых версий пакетов, обновляемых централизованно, с кодом проектов.

Пакеты следует устанавливать глобально в том случае, когда они представляют собой некие утилиты, вызываемые из командной строки, которые используются во множестве проектов.

Подобные пакеты можно устанавливать и локально, запуская предоставляемые ими утилиты командной строки с использованием npx, но некоторые пакеты, всё же, лучше устанавливать глобально. К таким пакетам, которые вам, вполне возможно, знакомы, можно отнести, например, следующие:

О зависимостях проектов

Когда пакет следует рассматривать как обычную зависимость проекта, необходимую для обеспечения его функционирования, а когда — как зависимость разработки?

При установке пакета с помощью команды вида npm install

Зависимости разработки — это пакеты, которые нужны в процессе разработки проекта, в ходе его обычного функционирования они не требуются. К таким пакетам относятся, например инструменты тестирования, Webpack, Babel.

Утилита npx

Сейчас мы поговорим об одной весьма мощной команде, npx, которая появилась в npm 5.2. Одной из её возможностей является запуск исполняемых файлов, входящих в состав npm-пакетов. Мы уже рассматривали использование npx для запуска подобного файла из пакета cowsay. Теперь поговорим об этом подробнее.

▍Использование npx для упрощения запуска локальных команд

Node.js-разработчики опубликовали множество исполняемых файлов (утилит) в виде пакетов, которые предполагалось устанавливать глобально, что обеспечивало удобный доступ к их возможностям, так как запускать их из командной строки можно было, просто введя имя соответствующей команды. Однако работать в такой среде было весьма некомфортно в том случае, если требовалось устанавливать разные версии одних и тех же пакетов.

▍Выполнение утилит без необходимости их установки

В npx имеется ещё одна интереснейшая возможность, благодаря которой утилиты можно запускать без их предварительной установки. Полезно это, в основном, по следующим причинам:

Если же пакет cowsay не будет установлен глобально, подобная команда выдаст ошибку.

Утилита npx позволяет выполнять подобные команды без их установки. Выглядит это, в рамках нашего примера, так:

Такая команда сработает, но, хотя «говорящая» корова, по большому счёту, особой пользы не приносит, тот же самый подход можно использовать и для выполнения куда более полезных команд. Вот несколько примеров:

▍Запуск JavaScript-кода с использованием различных версий Node.js

Это позволяет отказаться от использования инструментов наподобие nvm или других менеджеров версий Node.js.

▍Запуск произвольных фрагментов кода, доступных по некоему адресу

Npx позволяет запускать не только код, опубликованный в npm. В частности, если у вас есть ссылка на некий фрагмент кода (скажем, опубликованного на GitHub gist), запустить его можно так:

Конечно, при выполнении подобного кода нельзя забывать о безопасности. Npx даёт в руки разработчика большие возможности, но они означают и большую ответственность.

▍Итоги

Сегодня мы поговорили о некоторых полезных механизмах npm и об использовании npx. На данном этапе у вас должно сложиться базовое понимание устройства npm и методов работы с этим пакетным менеджером. Если вы хотите более глубоко изучить npm — обратитесь к странице документации проекта и побольше экспериментируйте.

В следующий раз мы обсудим некоторые базовые механизмы Node.js, понимание которых необходимо для успешной разработки приложений для этой платформы.

Уважаемые читатели! Пользуетесь ли вы npx?

How To Use Node.js Modules with npm and package.json

How to use npm. Смотреть фото How to use npm. Смотреть картинку How to use npm. Картинка про How to use npm. Фото How to use npm

The author selected the Open Internet/Free Speech Fund to receive a donation as part of the Write for DOnations program.

Introduction

Because of such features as its speedy Input/Output (I/O) performance and its basis in the well-known JavaScript language, Node.js has quickly become a popular runtime environment for back-end web development. But as interest grows, larger applications are built, and managing the complexity of the codebase and its dependencies becomes more difficult. Node.js organizes this complexity using modules, which are any single JavaScript files containing functions or objects that can be used by other programs or modules. A collection of one or more modules is commonly referred to as a package, and these packages are themselves organized by package managers.

The Node.js Package Manager (npm) is the default and most popular package manager in the Node.js ecosystem, and is primarily used to install and manage external modules in a Node.js project. It is also commonly used to install a wide range of CLI tools and run project scripts. npm tracks the modules installed in a project with the package.json file, which resides in a project’s directory and contains:

As you create more complex Node.js projects, managing your metadata and dependencies with the package.json file will provide you with more predictable builds, since all external dependencies are kept the same. The file will keep track of this information automatically; while you may change the file directly to update your project’s metadata, you will seldom need to interact with it directly to manage modules.

In this tutorial, you will manage packages with npm. The first step will be to create and understand the package.json file. You will then use it to keep track of all the modules you install in your project. Finally, you will list your package dependencies, update your packages, uninstall your packages, and perform an audit to find security flaws in your packages.

Prerequisites

To complete this tutorial, you will need:

Step 1 — Creating a package.json File

We begin this tutorial by setting up the example project—a fictional Node.js locator module that gets the user’s IP address and returns the country of origin. You will not be coding the module in this tutorial. However, the packages you manage would be relevant if you were developing it.

First, you will create a package.json file to store useful metadata about the project and help you manage the project’s dependent Node.js modules. As the suffix suggests, this is a JSON (JavaScript Object Notation) file. JSON is a standard format used for sharing, based on JavaScript objects and consisting of data stored as key-value pairs. If you would like to learn more about JSON, read our Introduction to JSON article.

Since a package.json file contains numerous properties, it can be cumbersome to create manually, without copy and pasting a template from somewhere else. To make things easier, npm provides the init command. This is an interactive command that asks you a series of questions and creates a package.json file based on your answers.

Using the init Command

First, set up a project so you can practice managing modules. In your shell, create a new folder called locator :

Then move into the new folder:

Now, initialize the interactive prompt by entering:

You will receive the following output:

Note: Node.js packages are expected to follow the Semantic Versioning (semver) guide. Therefore, the first number will be the MAJOR version number that only changes when the API changes. The second number will be the MINOR version that changes when features are added. The last number will be the PATCH version that changes when bugs are fixed.

Press ENTER so the default version of 1.0.0 is accepted.

The init command will then ask for the project’s git repository, which may live on a service such as GitHub (for more information, see GitHub’s Repository documentation). You won’t use this in this example, so leave it empty as well.

At this point, you would review your licensing options and decide what’s best for your project. For more information on different types of open source licenses, see this license list from the Open Source Initiative. If you do not want to provide a license for a private repository, you can type UNLICENSED at the prompt. For this sample, use the default ISC license, and press ENTER to finish this process.

The init command will now display the package.json file it’s going to create. It will look similar to this:

Once the information matches what you see here, press ENTER to complete this process and create the package.json file. With this file, you can keep a record of modules you install for your project.

Now that you have your package.json file, you can test out installing modules in the next step.

Step 2 — Installing Modules

It is common in software development to use external libraries to perform ancillary tasks in projects. This allows the developer to focus on the business logic and create the application more quickly and efficiently by utilizing tools and code that others have written that accomplish tasks one needs.

For example, if our sample locator module has to make an external API request to get geographical data, we could use an HTTP library to make that task easier. Since our main goal is to return pertinent geographical data to the user, we could install a package that makes HTTP requests easier for us instead of rewriting this code for ourselves, a task that is beyond the scope of our project.

Let’s run through this example. In your locator application, you will use the axios library, which will help you make HTTP requests. Install it by entering the following in your shell:

When the library is installed, you will see output similar to the following:

Now, open the package.json file, using a text editor of your choice. This tutorial will use nano :

You’ll see a new property, as highlighted in the following:

Note: You may have noticed the ^ before the version number for the axios dependency. Recall that semantic versioning consists of three digits: MAJOR, MINOR, and PATCH. The ^ symbol signifies that any higher MINOR or PATCH version would satisfy this version constraint. If you see

at the beginning of a version number, then only higher PATCH versions satisfy the constraint.

Development Dependencies

Packages that are used for the development of a project but not for building or running it in production are called development dependencies. They are not necessary for your module or application to work in production, but may be helpful while writing the code.

For example, it’s common for developers to use code linters to ensure their code follows best practices and to keep the style consistent. While this is useful for development, this only adds to the size of the distributable without providing a tangible benefit when deployed in production.

Install a linter as a development dependency for your project. Try this out in your shell:

This will show the following:

Automatically Generated Files: node_modules and package-lock.json

When you first install a package to a Node.js project, npm automatically creates the node_modules folder to store the modules needed for your project and the package-lock.json file that you examined earlier.

The node_modules folder contains every installed dependency for your project. In most cases, you should not commit this folder into your version controlled repository. As you install more dependencies, the size of this folder will quickly grow. Furthermore, the package-lock.json file keeps a record of the exact versions installed in a more succinct way, so including node_modules is not necessary.

Installing from package.json

With your package.json and package-lock.json files, you can quickly set up the same project dependencies before you start development on a new project. To demonstrate this, move up a level in your directory tree and create a new folder named cloned_locator in the same directory level as locator :

Move into your new directory:

Now copy the package.json and package-lock.json files from locator to cloned_locator :

To install the required modules for this project, type:

Before moving to the next section, return to the locator folder:

Global Installations

So far, you have been installing npm modules for the locator project. npm also allows you to install packages globally. This means that the package is available to your user in the wider system, like any other shell command. This ability is useful for the many Node.js modules that are CLI tools.

For example, you may want to blog about the locator project that you’re currently working on. To do so, you can use a library like Hexo to create and manage your static website blog. Install the Hexo CLI globally like this:

Test that the package was successfully installed by typing:

You will see output similar to:

Now that you can install modules, in the next section you will practice techniques to administer your dependencies.

Step 3 — Managing Modules

A complete package manager can do a lot more than install modules. npm has over 20 commands relating to dependency management available. In this step, you will:

Listing Modules

If you would like to know which modules are installed in a project, it would be easier to use the list or ls command instead of reading the package.json directly. To do this, enter:

You will see output like this:

You will see output like the following:

Updating Modules

It is a good practice to keep your npm modules up to date. This improves your likelihood of getting the latest security fixes for a module. Use the outdated command to check if any modules can be updated:

You will get output like the following:

It seems that you can update eslint to a more recent version. Use the update or up command like this:

The output of the command will contain the version installed:

To see which version of eslint that you are using now, you can use npm ls using the package name as an argument:

The output will resemble the npm ls command you used before, but include only the eslint package’s versions:

If you wanted to update all modules at once, then you would enter:

Uninstalling Modules

The npm uninstall command can remove modules from your projects. This means the module will no longer be installed in the node_modules folder, nor will it be seen in your package.json and package-lock.json files.

Removing dependencies from a project is a normal activity in the software development lifecycle. A dependency may not solve the problem as advertised, or may not provide a satisfactory development experience. In these cases, it may better to uninstall the dependency and build your own module.

Imagine that axios does not provide the development experience you would have liked for making HTTP requests. Uninstall axios with the uninstall or un command by entering:

Your output will be similar to:

It doesn’t explicitly say that axios was removed. To verify that it was uninstalled, list the dependencies once again:

Now, we only see that eslint is installed:

This shows that you have successfully uninstalled the axios package.

Auditing Modules

npm provides an audit command to highlight potential security risks in your dependencies. To see the audit in action, install an outdated version of the request module by running the following:

npm is telling you that you have deprecated packages and vulnerabilities in your dependencies. To get more details, audit your entire project with:

The audit command shows tables of output highlighting security flaws:

You will see similar output to:

npm was able to safely update two of the packages, decreasing your vulnerabilities by the same amount. However, you still have three deprecated packages in your dependencies. The audit fix command does not always fix every problem. Although a version of a module may have a security vulnerability, if you update it to a version with a different API then it could break code higher up in the dependency tree.

As mentioned before, this is not recommended unless you are sure that it won’t break functionality.

Conclusion

In this tutorial, you went through various exercises to demonstrate how Node.js modules are organized into packages, and how these packages are managed by npm. In a Node.js project, you used npm packages as dependencies by creating and maintaining a package.json file—a record of your project’s metadata, including what modules you installed. You also used the npm CLI tool to install, update, and remove modules, in addition to listing the dependency tree for your projects and checking and updating modules that are outdated.

In the future, leveraging existing code by using modules will speed up development time, as you don’t have to repeat functionality. You will also be able to create your own npm modules, and these will in turn will be managed by others via npm commands. As for next steps, experiment with what you learned in this tutorial by installing and testing the variety of packages out there. See what the ecosystem provides to make problem solving easier. For example, you could try out TypeScript, a superset of JavaScript, or turn your website into mobile apps with Cordova. If you’d like to learn more about Node.js, see our other Node.js tutorials.

Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.

Источники информации:

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

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