Node js windows registry

Read and Write to the Windows registry in-process from Node.js. Easily set application file associations and other goodies.

Projects that are alternatives of or similar to windows-registry-node

React Ckeditor

CKEditor component for React with plugin and custom event listeners support

Stars: ✭ 124 (+18.1%)

Mutual labels:  npm-module

Darkmode.js

🌓 Add a dark-mode / night-mode to your website in a few seconds

Stars: ✭ 2,339 (+2127.62%)

Mutual labels:  npm-module

pwainit

Turn your existing website to Progressive Web App or Initiate PWA project using single command!!. ‘npm i -g pwainit’ to install pwainit and get started 🚀

Stars: ✭ 45 (-57.14%)

Mutual labels:  npm-module

React Native Color Wheel

🌈 A react native reusable and color picker wheel

Stars: ✭ 137 (+30.48%)

Mutual labels:  npm-module

Reactopt

A CLI React performance optimization tool that identifies potential unnecessary re-rendering

Stars: ✭ 1,975 (+1780.95%)

Mutual labels:  npm-module

Abort Controller

An implementation of WHATWG AbortController interface.

Stars: ✭ 213 (+102.86%)

Mutual labels:  npm-module

Discord.js Musicbot Addon

This DOES NOT WORK any more. This repo only serves as an archive for is anyone wants to pickup my work. You may still join the discord however.

Stars: ✭ 109 (+3.81%)

Mutual labels:  npm-module

simple-load-script

Very simple promise based script loader and JSONP

Stars: ✭ 13 (-87.62%)

Mutual labels:  npm-module

Node Regedit

Read, Write, List and do all sorts of funky stuff to the windows registry using node.js and windows script host

Stars: ✭ 178 (+69.52%)

Mutual labels:  npm-module

Singlespotify

🎵 Create Spotify playlists based on one artist through the command line

Stars: ✭ 254 (+141.9%)

Mutual labels:  npm-module

Tanam

Plug-n-play CMS for websites on Firebase

Stars: ✭ 139 (+32.38%)

Mutual labels:  npm-module

Cerebral

Declarative state and side effects management for popular JavaScript frameworks

Stars: ✭ 1,946 (+1753.33%)

Mutual labels:  npm-module

Zoom

Javascript library to do pinch zoom that preserves scale and rotation correctly.

Stars: ✭ 130 (+23.81%)

Mutual labels:  npm-module

ifto

A simple debugging module for AWS Lambda (λ) timeout

Stars: ✭ 72 (-31.43%)

Mutual labels:  npm-module

Tspath

TypeScript path alias resolver

Stars: ✭ 115 (+9.52%)

Mutual labels:  npm-module

Jsonexport

{} → 📄 it’s easy to convert JSON to CSV

Stars: ✭ 208 (+98.1%)

Mutual labels:  npm-module

fetch-action-creator

Fetches using standardized, four-part asynchronous actions for redux-thunk.

Stars: ✭ 28 (-73.33%)

Mutual labels:  npm-module

Ts ci

✅ Continuous integration setup for TypeScript projects via GitHub Actions.

Stars: ✭ 225 (+114.29%)

Mutual labels:  npm-module

Read and Write to the Windows registry in-process from Node.js. Easily set application file associations and launch processes as an Administrator.

Install

This library interacts with native Windows APIs. To add this module to your Node application, install the package:

npm install windows-registry

To install node modules that require compilation on Windows, make sure you have installed the necessary build tools. Specifically, we need npm install -g node-gyp, a cross-platform cli written in Node.js for native addon modules for Node.js.

To install node-gyp, install python v2.7.3 and Visual Studio 2013 build tools. You do not need to install the full Visual Studio, only the build tools are required. Once the build tools are installed, you should be able to do npm install -g node-gyp.

Creating File Associations

To create a file association, you can call the fileAssociation.associateExeForFile API, which will make windows assign a default program for an arbitrary file extension:

var utils = require('windows-registry').utils;
utils.associateExeForFile('myTestHandler', 'A test handler for unit tests', 'C:\\path\\to\\icon', 'C:\\Program Files\\nodejs\\node.exe %1', '.zzz');

After running the code above, you will see files with the extension of .zzz will be automatically associated with the Node program and their file icon will be changed to the Node file icon.

'GIF showing file association'

Reading and Writing to the Windows Registry

This library implements only a few of the basic registry commands, which allow you to do basic CRUD
operations for keys in the registry.

Opening a Registry Key

Registry keys can be opened by either opening a predefined registry key defined in the windef module:

var Key = require('windows-registry').Key;
var key = new Key(windef.HKEY.HKEY_CLASSES_ROOT, '.txt', windef.KEY_ACCESS.KEY_ALL_ACCESS);

Or you can open a sub key from an already opened key:

var Key = require('windows-registry').Key;
var key = new Key(windef.HKEY.HKEY_CLASSES_ROOT, '', windef.KEY_ACCESS.KEY_ALL_ACCESS);
var key2 = key.openSubKey('.txt', windef.KEY_ACCESS.KEY_ALL_ACCESS);

And don’t forget to close your key when you’re done. Otherwise, you will leak native resources:

Creating a Key

Creating a key just requires that you have a Key object by either using the predefined keys within the windef.HKEY or opening a subkey from an existing key.

var Key = require('windows-registry').Key;
// predefined key
var key = new Key(windef.HKEY.HKEY_CLASSES_ROOT, '', windef.KEY_ACCESS.KEY_ALL_ACCESS);
var createdKey = key.createSubKey('\test_key_name', windef.KEY_ACCESS.KEY_ALL_ACCESS);

Deleting a Key

To delete a key just call the Key.deleteKey() function.

Writing a Value to a Key

To write a value, you will again need a Key object and just need to call the Key.setValue function:

var Key = require('windows-registry').Key,
	windef = require('windows-registry').windef;

var key = new Key(windef.HKEY.HKEY_CLASSES_ROOT, '.txt', windef.KEY_ACCESS.KEY_ALL_ACCESS);
key.setValue('test_value_name', windef.REG_VALUE_TYPE.REG_SZ, 'test_value');

Get a Value From a Key

To get a value from a key, just call Key.getValue:

var value = key.getValue('test_value_name');

The return value depends on the type of the key (REG_SZ for example will give you a string).

Launching a Process as an Admin

To launch a process as an Administrator, you can call the utils.elevate API, which will launch a process as an Administrator causing the UAC (User Account Control) elevation prompt to appear if required. This is similar to the Windows Explorer command «Run as administrator». Pass in FILEPATH to the process you want to elevate. Pass in anyPARAMETERS to run with the process. Since this is an asynchronous call, pass in a callback to handle user’s selection.

var utils = require('windows-registry').utils;
utils.elevate('C:\\Program Files\\nodejs\\node.exe', 'index.js', function (err, result){console.log(result);});

The process you want to launch with admin access will only be launched after the callback is called and only if the user clicks Yes in the UAC prompt. Otherwise, the process will not be launched. If the user is already running as an admin, the UAC prompt will not be triggered and the process you provided will be launched as an administrator automatically.

'GIF showing launch process as an admin'

More Docs?

Make your way over to the tests section to see how the module can be used.

Note that the project description data, including the texts, logos, images, and/or trademarks,
for each open source project belongs to its rightful owner.
If you wish to add or remove any projects, please contact us at [email protected].

kandi X-RAY | windows-registry-node Summary

kandi X-RAY | windows-registry-node Summary

windows-registry-node is a JavaScript library typically used in Server, Runtime Evironment, Nodejs, NPM applications. windows-registry-node has no bugs, it has no vulnerabilities, it has a Permissive License and it has low support. You can install using ‘npm i windows-registry-fixed’ or download it from GitHub, npm.

Read and Write to the Windows registry in-process from Node.js. Easily set application file associations and other goodies.

Support

    windows-registry-node has a low active ecosystem.

    It has 84 star(s) with 37 fork(s). There are 9 watchers for this library.

    It had no major release in the last 12 months.

    There are 14 open issues and 13 have been closed. On average issues are closed in 45 days. There are 9 open pull requests and 0 closed requests.

    It has a neutral sentiment in the developer community.

    The latest version of windows-registry-node is v0.0.2

Quality

    windows-registry-node has 0 bugs and 0 code smells.

Security

    windows-registry-node has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.

    windows-registry-node code analysis shows 0 unresolved vulnerabilities.

    There are 0 security hotspots that need review.

License

    windows-registry-node is licensed under the MIT License. This license is Permissive.

    Permissive licenses have the least restrictions, and you can use them in most projects.

Reuse

    windows-registry-node releases are available to install and integrate.

    Deployable package is available in npm.

    Installation instructions, examples and code snippets are available.

Top functions reviewed by kandi — BETA

kandi’s functional review helps you automatically verify the functionalities of the libraries and avoid rework.
Currently covering the most popular Java, JavaScript and Python libraries. See a

Sample of windows-registry-node

Get all kandi verified functions for this library.

windows-registry-node Key Features

No Key Features are available at this moment for

windows-registry-node

.

windows-registry-node Examples and Code Snippets

No Code Snippets are available at this moment for

windows-registry-node

.

Vulnerabilities

No vulnerabilities reported

Install windows-registry-node

This library interacts with native Windows APIs. To add this module to your Node application, install the package:. To install node modules that require compilation on Windows, make sure you have installed the necessary build tools. Specifically, we need npm install -g node-gyp, a cross-platform cli written in Node.js for native addon modules for Node.js. To install node-gyp, install python v2.7.3 and Visual Studio 2013 build tools. You do not need to install the full Visual Studio, only the build tools are required. Once the build tools are installed, you should be able to do npm install -g node-gyp.

Support

For any new features, suggestions and bugs create an issue on GitHub.
If you have any questions check and ask questions on community page Stack Overflow .

Find more information at:

Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items

Find more libraries

Время на прочтение5 мин

Количество просмотров59K

Npm — это повседневный рабочий инструмент Node.js-разработчиков. Это, в буквальном смысле, нечто такое, чем мы пользуемся ежедневно и по несколько раз на дню. Это — одна из частей экосистемы Node.js, которая привела эту платформу к успеху.

Одним из самых важных и полезных свойств интерфейса командной строки npm является то, что этот интерфейс поддаётся глубокой настройке. Возможности по его настройке поистине огромны. Это позволяет эффективно работать с npm всем категориям пользователей — от крупных организаций до самостоятельных разработчиков.

Одним их механизмов настройки npm является файл .npmrc. Я уже давно наблюдаю за тем, как вокруг этого файла разворачиваются дискуссии. Особенно памятно мне то время, когда я думал, что с помощью этого файла можно поменять имя директории node_modules. В течение длительного времени я не вполне понимал того, насколько полезным может быть .npmrc, да и того, как им вообще пользоваться.

Поэтому сегодня я хочу рассказать о некоторых возможностях по настройке рабочего окружения Node.js с использованием .npmrc. Мне эти настройки помогают быть эффективнее при подготовке Node.js-модулей и при долгосрочной работе над приложениями.

Немного более продвинутая, чем обычно, автоматизация команды npm init

Когда создают новый модуль с нуля, работу обычно начинают с команды npm init. Некоторые разработчики кое-чего об этой команде не знают. Дело в том, что процесс создания новых модулей можно очень сильно автоматизировать, прибегнув к командам вида npm config set ..., которые позволяют задавать варианты, подставляемые по умолчанию тогда, когда npm init начинает задавать вопросы о новом проекте.

А именно, так можно указать своё имя, адрес электронной почты, URL сайта, сведения о лицензии, начальную версию модуля. Речь идёт о следующих командах:

npm config set init.author.name "Hiro Protagonist"
npm config set init.author.email "hiro@showcrash.io"
npm config set init.author.url "http://hiro.snowcrash.io"
npm config set init.license "MIT"
npm config set init.version "0.0.1"

В этом примере я задал некоторые значения, используемые по умолчанию для разработчика Hiro. Личные данные разработчиков меняются не очень часто, поэтому установка некоторых значений, применяемых по умолчанию, позволяет не вводить их каждый раз вручную

Кроме того, тут задана пара значений, имеющих отношение к модулям.

Первое — это лицензия, которая автоматически будет предложена командой npm init. Лично я предпочитаю использовать лицензию MIT. Большинство других Node.js-разработчиков поступают так же. Таким образом, тут можно задать всё, что хотите. Возможность почти автоматически выбирать используемую вами лицензию — это хорошая оптимизация.

Второе значение — это начальная версия модуля. Это — мелочь, но меня эта возможность прямо-таки осчастливила. Дело в том, что каждый раз, когда я принимался за создание модуля, мне не хотелось начинать с версии 1.0.0, предлагаемой по умолчанию npm init. Я всегда устанавливал номер версии в 0.0.1, а затем, по мере работы над модулем, увеличивал её с использованием команд вида npm version [ major | minor | patch ].

Изменение стандартного реестра npm

Прогресс не стоит на месте, поэтому в экосистеме npm возникает всё больше возможностей по работе с реестрами пакетов. Например, может понадобиться использовать в качестве реестра кэш модулей, которые, как известно разработчику, понадобятся для приложения. Или, может быть, кто-то решит использовать реестр модулей, прошедших какую-то дополнительную проверку и сертификацию. Есть даже отдельный реестр модулей для Yarn, но это тема, хотя и очень интересная, к нашему сегодняшнему разговору не относится.

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

npm config set registry "https://my-custom-registry.registry.nodesource.io/"

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

npm config set registry "https://registry.npmjs.com/"

Параметр loglevel и настройка того, что выводит в консоль команда npm install

Когда вы устанавливаете модули с помощью команды npm install, на вас обрушивается целый водопад информации. Средства командной строки, по умолчанию, ограничивают объём подобных сведений. Есть разные степени подробности выводимых сведений. Это можно настроить либо при установке npm, либо задав параметры, записываемые в .npmrc и применяемые по умолчанию. Делается это с помощью команды вида npm config set loglevel=»..». Вот варианты значений параметра loglevel — от самого «немногословного», до самого «говорливого»:

  • silent
  • error
  • warn
  • http
  • info
  • verbose
  • silly

Вот как выглядит установка пакета при использовании параметра loglevel, в который записано silent.

image

Silent-режим вывода сведений при установке пакетов

А вот что будет, если установить loglevel в значение silly.

image

Silly-режим вывода сведений при установке пакетов

Если вам нужно, чтобы при установке пакетов выводилось бы немного больше (или немного меньше) информации, чем обычно, значение loglevel, используемое по умолчанию, можно изменить. Например — так:

npm config set loglevel="http"

Если вы немного поэкспериментируете с этим параметром и решите сбросить его к значению, используемому CLI npm по умолчанию, выполните следующую команду:

npm config set loglevel="warn"

Изменение места, в которое npm, по умолчанию, устанавливает глобальные модули

Это — просто потрясающая возможность. Для того чтобы npm устанавливал бы глобальные пакеты в новое место, придётся немного повозиться, но эти усилия стоят результата. Речь идёт о том, что с помощью нескольких команд можно изменить то место, куда npm, по умолчанию, устанавливает глобальные модули. Обычно они устанавливаются в привилегированную системную папку, что требует административных полномочий. В системах, основанных на UNIX, это означает, что для установки глобальных модулей требуется команда sudo.

Если записать в параметр prefix путь к непривилегированной директории, например, ~/.global-modules, это значит, что вам не нужно будет аутентифицироваться при установке глобальных модулей. Это — одна из сильных сторон такой настройки. Другая сильная сторона — это то, что модули, устанавливаемые глобально, больше не будут находиться в системной директории, что снижает вероятность того, что какой-нибудь опасный модуль (намеренно или нет) сделает с системой что-то нехорошее.

Для начала создадим новую папку с именем global-modules и запишем её в prefix:

mkdir ~/.global-modules
npm config set prefix "~/.global-modules"

Далее, если у нас нет файла ~/.profile, создадим такой файл в корневой директории пользователя. Добавим в этот файл следующее:

export PATH=~/.global-modules/bin:$PATH

Эта строчка в файле ~/.profile приведёт к добавлению папки global-modules в PATH и позволит использовать эту папку для установки глобальных модулей npm.

Теперь, в терминале, нужно выполнить следующую команду для обновления PATH с использованием только что отредактированного файла ~/.profile:

source ~/.profile

Итоги

Эта статья написана для того чтобы помочь всем желающим настроить окружение для Node.js-разработки именно так, как им нужно. Вот документация по команде npm config. Вот — по файлу .npmrc.

Как вы настраиваете npm?

Did you observe nodejs project has several RC dotfiles like .npmrc, and .babelrc generated in a nodejs project?

In this tutorial, learn about the contents of npmrc with the below things

  • npmrc file create
  • how to add a registry and scope multiple registries
  • npm config set, get the list
  • npmrc auth token configuration
  • npmrc file location in windows
  • How to create an npm runtime configuration
  • npmrc sample file example
  • parsing RC file in nodejs

For example, We have different RC files in different applications

.npmrc .babelrc .netrc .vuerc .yarnrc

npmrc dotfiles

.npmrc is an npm runtime configuration file that contains the following things related to the nodejs project as well as the application. This will be used by npm commands to run based on configured settings

  • environment variables
  • npm registry configuration
  • auth configurations

normally you can pass command-line options to the npm command. This is a command level.

suppose you want to change the log level for the npm install command.

The same above command level options can be replaced by placing loglevel in the npmrc file as below

In the same way, we can configure different settings in this file🔗 .npmrc file can be created as

  • globally
  • OS user
  • Application-level rc files are configuration settings for a module or a project in a Unix operating system.

you can list out the npmrc file content using the below command

you can update the npmrc with the npm config set command

configuration settings can be retrieved with the npm config get command

.npmrc file can be configured to have environment variable

What is the .npmrc file location in Windows and MAC?

In Windows, Let’s see the path of the file location.

.npmrc file is created in windows for nodejs installation globally with below location

if you want settings such as logging need at the OS user level, you can find below the location

Another location for npmrc will be created while installation of nodejs setup.

also

you can also check npm location on any OS using the below command

How to create an npmrc file?

You can create npmrc files using the below approaches

  • manually with any editor
  • npm login command

.npmrc file content can be similar to the ini file format

change loglevel for npm install command output

npm install command gives a lot of useful information to the console.

This can be controlled with loglevel settings via command line or npmrc loglevel settings

you can set the command to update the log level.

This update the npmrc file with the below entries

There are other loglevel settings like silent, HTTP,warn,info,error, andsilly`
npmrc environment variables

How to update proxy configuration in npmrc file?

npm config command has a set command to set the below values with proxy url addresses

  • http-proxy
  • https-proxy
  • proxy details

npmrc multiple registries

registration is a repository of open-source javascript npm libraries which can be used by dependent application users.

nodejs uses the default registry for npm packages to download dependencies.

you can create custom scope packages with the below command

You can create and configure multiple registries in the npmrc file

Here is a code for npmrc multiple registry example

npmrc auth token

sometimes, We want to add auth token to authorize the registration of scope modules.

For example, font awesome comes with a free and licensed version.

the free version can be downloaded directly without auth token.

But for the licensed version, you need to supply auth token which is a secret key.

So you will not directly configure in npmrc file

first, create an environment variable for auth_token

Next run below command

authorization token will not be committed to a git repository.

You can also add in .env files if you are using env files in your project which are not committed to git due to this is added in .gitignore by default.

npmrc parser in nodejs

There are multiple libraries to parse RC files similarly to a JSON file,

There are npm libraries like rc🔗 used to parse from javascript code.

npmrc sample file example

Let’s see a sample npmrc file in the node project.

comments always started with # or ; that will be ignored by npm commands

Conclusion

In this tutorial, You learned about npmrc files with examples in nodejs projects.

Download Windows Speedup Tool to fix errors and make PC run faster

Node Package Manager (NPM) is installed on your Windows computer once you install Node.js. It is a package manager for modules of Node.js, and it’s ready to run on your Windows PC. In this article, we will show you how to install NPM on Windows 11/10, step by step.

Install NPM on Windows

NPM is a registry and library for JavaScript apps with a command line for interacting with the repository to help in installing and managing package versions and other dependencies. The repository is used for publishing open-source projects in Node.js.

Why should I install NPM?

It is possible to manage your project packages yourself. However, when the project grows, you will only be able to handle some of the projects. At this point, you need NPM to handle your dependencies and manage your packages. With NPM, you define all dependencies and packages in a package.json file, and when you want to get started, you install npm.

The NPM software is ready to run on your PC when you install Node.js. To install Node.js and NPM on Windows 11 or Windows 10 computers, use either of the two methods below:

  1. Use Node.js installer
  2. Use Chocolatey

Let us look at these methods in detail.

1] Use Node.js installer

How to Install NPM on Windows 11/10 step by step

This method involves installing libraries for Node.js on the client operating system. So, to download and install Node.js on Windows 11 or Windows 10, follow the steps below:

  • Open your browser and go to the official Node.js download page.
  • Here, locate the correct binary. In this case, click LTS Recommended For Most Users, and download a 64-bit Windows Installer (.msi) file.
  • Go to the browser downloads and click the file to start the installation process.
  • Click Run when the Open File – Security Warning wizard appears.
  • Follow the other on-screen steps to complete the installation.

2] Use Chocolatey

How to Install NPM on Windows 11/10 step by step

To install NPM using Chocolatey on Windows 11 or Windows 10, use the following simple steps:

Search for Windows PowerShell in the search box and select Run as administrator.
Run the following commands, each at a time:

@powershell -NoProfile -ExecutionPolicy Bypass -Command “iex ((new-object wet.webclient).DownloadString(‘https://chocolatey.org/install.ps1’))” && SET PATH=%PATH%;%ALLUSERSPROFILE%\chocolatey\bin
cinst nodejs install

Note: You can run these scripts without PowerShell profiles.

That’s it for now. Hopefully, one of the methods works for you.

Read: Setup Node.js development environment on Windows computer

How do you check if NPM is installed?

To check if NPM is installed on your system, run the command C:\Users\Admin> node -v on either the Command Prompt or Windows PowerShell. If it is installed, you will get a notification about Node.js on your PC. If you get a message that it’s not installed, you can add the path manually.

Next: What does Javascript:void(0) mean how to fix Javascript:void(0) error?

What does Node.js do?

Node.js can perform several actions, such as generating page content and collecting data. It can also add, modify, and delete data from databases. Finally, you can use Node.js to open, delete, create, read, close, and write files on the system server.

Robert holds a B.Tech. He has a knack for solving problems in people’s lives. With his background in technology, he is able to write complex topics in simple, understandable terms. He enjoys writing all matters Windows.

Reader Interactions

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Driver epson l800 windows 10 64 bit
  • Активация защитника windows 10
  • Ошибка при установке windows 10 с флешки нет драйвера
  • Проверить подходит ли пк для windows 11 онлайн
  • Управление жестами мыши windows 10