Npm
Содержание:
- Expose Metrics: Measure anything
- Как Работает npm?
- Интересное
- Разница при выполнении команд
- Options
- Automated help
- Использование файла «package.json»
- Report Alerts: Errors / Uncaught Exceptions
- Usage
- t.map()
- Using npm Programmatically
- Bits and pieces
- Expose Functions: Trigger Functions remotely
- Файл package.json¶
Expose Metrics: Measure anything
PMX allows you to expose code metrics from your code to the PM2 monit command or the Keymetrics Dashboard, in realtime and over time.
4 measurements are available:
-
Simple metrics
eg. Monitor variable value
: Values that can be read instantly
-
Counter
eg. Downloads being processed, user connected
: Things that increment or decrement
-
Meter
eg. Request per minute for a http server
: Things that are measured as events / interval
-
Histogram
eg. Monitor the mean of execution of a query into database
: Keeps a reservoir of statistically relevant values biased towards the last 5 minutes to explore their distribution
This allow to expose values that can be read instantly.
var probe =pmx.probe();var metric =probe.metric({ name 'Realtime user',valuefunction(){returnObject.keys(users).length;}});var metric_2 =probe.metric({ name 'Realtime Value'});metric_2.set(23);
- name: Probe name
- value: (optional) function that allows to monitor a global variable
Things that increment or decrement.
var probe =pmx.probe();var counter =probe.counter({ name 'Current req processed'});http.createServer(function(req,res){counter.inc();req.on('end',function(){counter.dec();});});
name: Probe name
Things that are measured as events / interval.
var probe =pmx.probe();var meter =probe.meter({ name 'req/sec', samples 1});http.createServer(function(req,res){meter.mark();res.end({successtrue});});
- name: Probe name
- samples: (optional)(default: 1) Rate unit. Defaults to 1 sec.
- timeframe: (optional)(default: 60) timeframe over which events will be analyzed. Defaults to 60 sec.
Keeps a resevoir of statistically relevant values biased towards the last 5 minutes to explore their distribution.
var probe =pmx.probe();var histogram =probe.histogram({ name 'latency', measurement 'mean'});var latency =;setInterval(function(){ latency =Math.round(Math.random()*100);histogram.update(latency);},100);
- name: Probe name
- agg_type : (optional)(default: none) Can be , , , (default) or . It will impact the way the probe data are aggregated within the Keymetrics backend. Use if this is irrelevant (eg: constant or string value).
- alert : (optional)(default: null) For and probes. Creates an alert object (see below).
Как Работает npm?
Он работает, выполняя одну из своих двух ролей:
- Это широко используемый репозиторий для публикации проектов Node.js с открытым исходным кодом. Это означает, что это онлайн-платформа, где каждый может публиковать и делиться инструментами, написанными на JavaScript.
- npm – это инструмент командной строки, который помогает взаимодействовать с онлайн-платформами, такими как браузеры и серверы. Эта утилита помогает в установке и удалении пакетов, управлении версиями и зависимостями, необходимыми для запуска проекта.
Чтобы использовать npm, нужно сначала установить node.js, так как они связаны.

Утилита командной строки npm обеспечивает корректную работу node.js.
Чтобы использовать пакеты, ваш проект должен содержать файл с именем package.json. Внутри этого пакета вы найдёте метаданные, касающиеся проектов.
Метаданные показывают несколько аспектов проекта в следующем порядке:
- Название проекта
- Первоначальная версия
- Описание
- Точка входа
- Тестовые команды
- Репозиторий Git
- Ключевые слова
- Лицензия
- Зависимости
- DevDependencies
Метаданные помогают идентифицировать проект и служат основным источником информации о проекте.
Вот пример того, как вы можете идентифицировать проект по его метаданным:
{
"name": "hostinger-npm",
"version": "1.0.0",
"description": "npm guide for beginner",
"main": "beginner-npm.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": ,
"author": "Hostinger International",
"license": "MIT",
"dependencies": {
"express": "^4.16.4"
}
}
- Имя: hostinger-npm
- Версия: 1.0.0
- Это руководство по npm для начинающих
- Точка входа в проект или основной файл: beginner-npm.js
- Ключевые слова или теги для поиска проекта в репозитории: npm, example и basic
- Автор проекта: Hostinger International.
- Этот проект лицензирован в рамках MIT
- Зависимости или другие модули, которые использует этот модуль – express 4.16.4
Интересное
Инициализация нового пакета
Первое действие при создании нового пакета — :Если вопросы кажутся вам лишними и вы хотите их проскочить, используйте или :
Доступные скрипты
При работе над новым проектом вы, скорее всего, интересуетесь, что вообще можно запустить в его рамках. Можно открыть файл и проверить секцию :Но список доступных скриптов можно получить и через :Еще вариант — установить интерактивное меню () и запустить в папке проекта:
Установленные пакеты
Для проверки зависимостей тоже можно было бы зайти в , но есть вариант получше — :Для проверки пакетов, установленных глобально, подходит та же команда с соответствующим флагом — :
Запуск локально установленных исполняемых модулей
Мы установили пакет, в нем есть исполняемый модуль, но он работает только при запуске через npm-скрипты. Почему это так, и как этого избежать?
Когда мы передаем команду терминалу, он ищет исполняемый модуль с таким же названием по всем путям, которые перечислены в переменной окружения . Локально установленные пакеты регистрируют исполняемые файлы локально, поэтому они не перечислены в и не могут быть обнаружены.
При запуске исполняемых модулей через npm-скрипты менеджер пакетов добавляет дополнительную папку к , . Её можно найти, запустив . С помощью можно увидеть все доступные переменные окружения.
Хакатон PhotoHack Mobile
12–13 сентября, онлайн, беcплатно
tproger.ru
События и курсы на tproger.ru
В локально установленные пакеты размещают свои исполняемые модули. Запускаем в директории проекта:
Просто пишите , когда хотите запустить локально установленный исполняемый модуль.
Найти пакет в Интернете
В файле вы могли заметить запись . Для того, чтобы открыть соответствующий репозиторий в браузере, запустите команду . Команда выполняет ту же функцию для записи . Если вы хотите открыть пакет на официальном сайте, используйте команду .
Запуск скриптов до и после других скриптов
Вы скорее всего знакомы со скриптом , он позволяет определить код, который следует запустить перед скриптом . Оказывается, и скрипты можно создавать для любых других скриптов, в том числе кастомных:
Обновить версию пакета
Допустим, вы используете semver для управления версиями и хотите обновить версию перед очередным релизом. Можно открыть и сделать это вручную, но зачем?
Более простой способ — запустить команду с , или :
Еще несколько советов можно найти в специальном , где кроме этого собраны разные полезные инструменты и ссылки на ресурсы, связанные с npm.
Разница при выполнении команд
Кроме своих функциональных преимуществ, Yarn также имеет несколько новых полезных команд.
Установка зависимостей
npm install устанавливает зависимости с файла package.json. Команда yarn install – с файла yarn.lock.
yarn why
Если вам не понятно почему именно этот пакет установился, команда yarn why пройдется по графу зависимостей и поможет вам выяснить.
Добавления пакетов
Команда yarn add <package> позволяет добавлять зависимости также как команда npm install <package>, но также добавляет зависимость в package.json.
Обновления пакетов
Также как и npm update, команда yarn upgrade обновляет версии пакетов до последних версий.
yarn generate-lock-entry
Если вам нужно вручную сгенерировать файл yarn.lock, базируясь на зависимостях из package.json, используйте команду yarn generate-lock-entry. По сути это команда npm shrinkwrap, но ее нужно использовать очень аккуратно потому что файл yarn.lock, перезаписывается каждый раз при установке новой зависимости.
Улучшения npm в версии 5.0
В релиз пятой версии npm было добавлено три весомых улучшения:
1. Сохранения версий: был добавлен package-lock.json файл, и убрана команда npm-shrinkwrap. Это помогло решить проблемы с версиями зависимостей между установками на разных устройствах.
2. Улучшена производительность: npm 5 быстрее своих предшественников
3. Автоматическое добавление в package.json файл при выполнении команды npm install, в предыдущих версиях приходилась запускать эту команду з флагом –save.
npm vs Yarn: кто более надежен ?
До первого официального релиза Yarn, пользователи жаловались на проблемы с производительностью, но эти проблемы вскоре были решены. Так как Yarn поддерживается такой большой компанией как Facebook, все баги фиксят довольно быстро. По этому Yarn должен быть достаточно стабилен сейчас, но если вы столкнулись с какой то проблемой вы всегда можете вернуться к старому доброму npm.
Недостатки Yarn
Несмотря на то, что Yarn считается улучшенной версией npm, он все же имеет несколько нерешенных проблем. Например, одновременное использование npm и Yarn создает конфликты. Чтобы избежать подобных проблем, рекомендуется разделять проект на модули. Еще одной проблемой является большая необходимость в дисковом пространстве, так как Yarn сохраняет зависимости локально.
Options
--concurrency <n> Max number of concurrent HTTP requests to registry. (default: 8)--configFilePath <path> Directory of .ncurc config file (default: directory of `packageFile`).--configFileName <filename> Config file name (default: .ncurc.{json,yml,js})--cwd <path> Working directory in which npm will be executed.--dep <dep> Check one or more sections of dependencies only: prod, dev, peer, optional, bundle (comma-delimited).--doctor Iteratively installs upgrades and runs tests to identify breaking upgrades. Run "ncu --doctor" for detailed help. Add "-u" to execute.--enginesNode Include only packages that satisfy engines.node as specified in the package file.-e, --errorLevel <n> Set the error level. 1: exits with error code 0 if no errors occur. 2: exits with error code 0 if no packages need updating (useful for continuous integration). (default: 1)-f, --filter <matches> Include only package names matching the given string, comma-or-space-delimited list, or /regex/.-g, --global Check global packages instead of in the current project.--greatest DEPRECATED. Renamed to "--target greatest".-i, --interactive Enable interactive prompts for each dependency; implies -u unless one of the json options are set,-j, --jsonAll Output new package file instead of human-readable message.--jsonDeps Like `jsonAll` but only lists `dependencies`, `devDependencies`, `optionalDependencies`, etc of the new package data.--jsonUpgraded Output upgraded dependencies in json.-l, --loglevel <n> Amount to log: silent, error, minimal, warn, info, verbose, silly. (default: "warn")-m, --minimal Do not upgrade newer versions that are already satisfied by the version range according to semver.-n, --newest DEPRECATED. Renamed to "--target newest".-p, --packageManager <name> npm, yarn (default: "npm")-o, --ownerChanged Check if the package owner changed between current and upgraded version.--packageData <string> Package file data (you can also use stdin).--packageFile <path> Package file location (default: ./package.json).--pre <n> Include -alpha, -beta, -rc. (default: 0; default with --newest and --greatest: 1).--prefix <path> Current working directory of npm.-r, --registry <url> Third-party npm registry.--removeRange Remove version ranges from the final package version.--semverLevel <value> DEPRECATED. Renamed to --target.-s, --silent Don't output anything (--loglevel silent).-t, --target <value> Target version to upgrade to: latest, newest, greatest, minor, patch. (default: "latest")--timeout <ms> Global timeout in milliseconds. (default: no global timeout and 30 seconds per npm-registery-fetch).-u, --upgrade Overwrite package file with upgraded versions instead of just outputting to console.-x, --reject <matches> Exclude packages matching the given string, comma-or-space-delimited list, or /regex/.-V, --version output the version number-h, --help display help for command
Automated help
The help information is auto-generated based on the information commander already knows about your program. The default
help option is .
$ node ./examples/pizza --helpUsage: pizza An application forpizzas orderingOptions: -V, --version output the version number -p, --peppers Add peppers -c, --cheese <type> Add the specified type of cheese (default: "marble") -C, --no-cheese You do not want any cheese -h, --help display helpforcommand
A command is added by default if your command has subcommands. It can be used alone, or with a subcommand name to show
further help for the subcommand. These are effectively the same if the program has implicit help:
shell helpshell --helpshell help spawnshell spawn --help
You can display extra information by listening for «—help».
program.option('-f, --foo','enable some foo');program.on('--help',()=>{console.log('');console.log('Example call:');console.log(' $ custom-help --help');});
Yields the following help output:
Usage: custom-help Options: -f, --foo enable some foo -h, --help display help for commandExample call: $ custom-help --help
These allow you to customise the usage description in the first line of the help. The name is otherwise
deduced from the (full) program arguments. Given:
program.name("my-command").usage(" command")
The help will start with:
Usage: my-command command
Output help information and exit immediately. Optional callback cb allows post-processing of help text before it is displayed.
Output help information without exiting.
Optional callback cb allows post-processing of help text before it is displayed.
Get the command help information as a string for processing or displaying yourself. (The text does not include the custom help
from listeners.)
Override the default help flags and description. Pass false to disable the built-in help option.
program.helpOption('-e, --HELP','read more information');
You can explicitly turn on or off the implicit help command with and .
You can both turn on and customise the help command by supplying the name and description:
program.addHelpCommand('assist ','show assistance');
Использование файла «package.json»
Лучший способ управления локально установленными пакетами — это использование файла «package.json», который должен иметь как минимум
name и
version.
Поле
name должно состоять из строчных букв английского алфавита, подчёркиваний и тире. Оно определяет имя вашего модуля.
Поле
version определяет версию в формате x.x.x.
Пример:
JavaScript
{
«name»: «my-awesome-package»,
«version»: «1.0.0»
}
|
1 |
{ «name»»my-awesome-package», «version»»1.0.0» } |
Создать «package.json» можно командой с консоли:
npm init
| 1 | npm init |
Эта команда проведёт вас через процесс создания «package.json» в стиле вопрос-ответ.
Report Alerts: Errors / Uncaught Exceptions
(Specific to Keymetrics)
By default once PM2 is linked to Keymetrics, you will be alerted of any uncaught exception.
These errors are accessible in the Issue tab of Keymetrics.
If you need to alert about any critical errors you can do it programmatically:
var pmx =require('pmx');pmx.notify({ success false});pmx.notify('This is an error');pmx.notify(newError('This is an error'));
When an uncaught exception is happening you can track from which routes it has been thrown.
To do that you have to attach the middleware at then end of your routes mounting:
var pmx =require('pmx');app.get(''...);app.post(...);app.use(pmx.expressErrorHandler());
Usage
This utility is supposed to be run in the root directory of your Node.js project (that contains ).
Run to see all available top-level commands:
Run to see usage help for corresponding command.
is the default command and can be omitted so running is the same as .
It will find all your outdated deps and will ask to updated their versions in , one by one.
For example, here is what you will see if you use outdated version of module:
- will update version in to , but not immediately (see explanation below)
- will not update this module version.
- will try to find changelog url for the current module and open it in default browser.
- will …hm… finish update process and save all the changes to .
A note on saving changes to : when you choose to update some module’s version, won’t be immediately updated. It will be updated only after you will process all the outdated modules and confirm update or when you choose . So if in the middle of the update process you’ve changed your mind just press and will remain untouched.
If you want to check only some deps, you can use argument:
npm-upgrade babel-corenpm-upgrade '*babel*'npm-upgrade '!*babel*'npm-upgrade '*babel* !babel-transform-* !babel-preset-*'
If you want to check only a group of deps use these options:
Sometimes you just want to ignore newer versions of some dependency for some reason. For example, you use because of the old IE support and don’t want to suggest you updating it to . Or you use and know that the new version contains a bug that breaks your app.
You can handle these situations by ignoring such modules. You can do it in two ways: choosing during update process or using command.
- — will ignore only version . When the next version after will be published will suggest to update it. Can be used in example above.
- — will ignore all versions starting from . Can be used in example above.
- — will ignore all and versions.
- — will ignore all new versions.
And after that will ask about the ignore reason. The answer is optional but is strongly recommended because it will help to explain your motivation to your сolleagues and to yourself after a few months.
All the data about ignored modules will be stored in file next to your project’s .
- — will add a module from your deps to ignored list. You can either provide module name as optional argument or interactively select it from the list of project’s deps.
- — will show the list of currently ignored modules along with their ignored versions and reasons.
- — will remove modules from the ignored list. You can either provide module names as argument (separated by space) or interactively select them from the list of project’s deps.
Will try to find changelog url for provided module and open it in default browser.
t.map()
given a tree, return a tree of the same structure made up of the objects
returned by the callback which is executed at each node. think of the
‘s function, or python’s
-
:
object where the traversal will start. this could also be an array of
objects -
:
you can define the name of the children property with -
(last argument):
function to be executed at each node. this must return an object. the
function takes care of setting children. the arguments are:- : the current node
-
: the current node’s parent. note that this is the parent from
the new tree that’s being created.
returns: a new tree, mapped by the callback function
Using npm Programmatically
If you would like to use npm programmatically, you can do that.
It’s not very well documented, but it is rather simple.
Most of the time, unless you actually want to do all the things that
npm does, you should try using one of npm’s dependencies rather than
using npm itself, if possible.
Eventually, npm will be just a thin cli wrapper around the modules
that it depends on, but for now, there are some things that you must
use npm itself to do.
The function takes an object hash of the command-line configs.
The various functions take an array of
positional argument strings. The last argument to any
function is a callback. Some commands take other
optional arguments. Read the source.
You cannot set configs individually for any single npm function at this
time. Since is a singleton, any call to will
change the value for all npm commands in that process.
See for an example of pulling config values off of the
command line arguments using nopt. You may also want to check out to learn about all the options you can set there.
Bits and pieces
The first argument to is the array of strings to parse. You may omit the parameter to implicitly use .
If the arguments follow different conventions than node you can pass a option in the second parameter:
- ‘node’: default, is the application and is the script being run, with user parameters after that
- ‘electron’: varies depending on whether the electron application is packaged
- ‘user’: all of the arguments from the user
For example:
program.parse(process.argv);program.parse();program.parse('-f','filename',{ from'user'});
The original and default behaviour is that the option values are stored
as properties on the program, and the action handler is passed a
command object with the options values stored as properties.
This is very convenient to code, but the downside is possible clashes with
existing properties of Command.
There are two new routines to change the behaviour, and the default behaviour may change in the future:
- : whether to store option values as properties on command object, or store separately (specify false) and access using
-
: whether to pass command to action handler,
or just the options (specify false)
program.storeOptionsAsProperties(false).passCommandToAction(false);program.name('my-program-name').option('-n,--name <name>');program.command('show').option('-a,--action <action>').action((options)=>{console.log(options.action);});program.parse(process.argv);constprogramOptions=program.opts();console.log(programOptions.name);
The Commander package includes its TypeScript Definition file.
If you use and stand-alone executable subcommands written as files, you need to call your program through node to get the subcommands called correctly. e.g.
node -r ts-node/register pm.ts
This factory function creates a new command. It is exported and may be used instead of using , like:
const{createCommand}=require('commander');constprogram=createCommand();
Commander is currently a CommonJS package, and the default export can be imported into an ES Module:
importcommanderfrom'commander';constprogram=commander.program;constnewCommand=newcommander.Command();
You can enable option in two ways:
- Use in the subcommands scripts. (Note Windows does not support this pattern.)
- Use the option when call the command, like . The option will be preserved when spawning subcommand process.
An executable subcommand is launched as a separate child process.
If you are using VSCode to debug executable subcommands you need to set the flag in your launch.json configuration.
By default Commander calls when it detects errors, or after displaying the help or version. You can override
this behaviour and optionally supply a callback. The default override throws a .
The override callback is passed a with properties number, string, and . The default override behaviour is to throw the error, except for async handling of executable subcommand completion which carries on. The normal display of error messages or version or help
is not affected by the override which is called after the display.
program.exitOverride();try{program.parse(process.argv);}catch(err){}
Expose Functions: Trigger Functions remotely
Remotely trigger functions from Keymetrics. These metrics takes place in the main Keymetrics Dashboard page under the Custom Action section.
Simple action allows to trigger a function from Keymetrics. The function takes a function as a parameter (reply here) and need to be called once the job is finished.
Example:
var pmx =require('pmx');pmx.action('db:clean',function(reply){clean.db(function(){reply({success true});});});
Scoped Actions are advanced remote actions that can be also triggered from Keymetrics.
Two arguments are passed to the function, data (optional data sent from Keymetrics) and res that allows to emit log data and to end the scoped action.
Example:
pmx.scopedAction('long running lsof',function(data,res){var child =spawn('lsof',);child.stdout.on('data',function(chunk){chunk.toString().split('\n').forEach(function(line){res.send(line);});});child.stdout.on('end',function(chunk){res.end('end');});child.on('error',function(e){res.error(e);});});
(Specific to Keymetrics)
This alert system can monitor a Probe value and launch an exception when hitting a particular value.
Example for a variable:
var metric =probe.metric({ name 'CPU usage',valuefunction(){return cpu_usage;}, alert { mode 'threshold', value 95, msg 'Detected over 95% CPU usage',funcfunction(){console.error('Detected over 95% CPU usage');}, cmp "<"}});
- mode : , .
- value : Value that will be used for the exception check.
- msg : String used for the exception.
- func : optional. Function declenched when exception reached.
- cmp : optional. If current Probe value is not , , to Threshold value the exception is launched. Can also be a function used for exception check taking 2 arguments and returning a bool.
- interval : optional, mode. Sample length for monitored value (180 seconds default).
- timeout : optional, mode. Time after which mean comparison starts (30 000 milliseconds default).
Файл package.json¶
Для более удобного управления конфигурацией и пакетами приложения в npm применяется файл конфигурации . Так, добавим в папку проекта новый файл :
Здесь определены только две секции: имя проекта — и его версия — . Это минимально необходимое определение файла . Данный файл может включать гораздо больше секций. Подробнее можно посмотреть в документации.
Далее удалим из проекта каталог . То есть в папке проекта будут два файла и .
Теперь снова добавим с помощью следующей команды:
Флаг указывает, что информацию о добавленном пакете надо добавить в файл .
И после выполнения команды, если мы откроем файл , то мы увидим информацию о пакете:
Информация обо всех добавляемых пакетах, которые используются при запуске приложения, добавляется в секцию .
Файл играет большую роль и может облегчить разработку в различных ситуациях. Например, при размещении в разных репозиториях нередко мы ограничены выделяемым дисковым пространством, тогда как папка со всеми загруженными пакетами может занимать довольно приличное пространство. В этом случае удобнее разместить основной код проекта без . В этом случае мы можем определить все пакеты в файле , а затем для загрузки всех пакетов выполнить команду
Эта команда возьмет определение всех пакетов из секций и загрузит их в проект.






