Исправление пути npm в Windows 8 и 10
много гуглил, пробовал переустановить узел.в JS с помощью официального установщика, но мой НПМ маршруты по-прежнему не работает.
это не работает
Я получаю сообщение об ошибке говоря отсутствует модуль npm-cli.js
2 часа гуглить позже я обнаружил обходной путь
А не просто’npm‘ я типа
но как я могу исправить свою установку nodejs, чтобы я мог просто ввести «npm»?
8 ответов:
вам нужно добавить C:\Program Files\nodejs к переменной среды PATH. Для этого выполните следующие действия:
- используйте глобальный поиск очарование для поиска «Переменные среды»
- Нажмите кнопку «изменить системные переменные среды»
- нажимаем «Переменные среды» в диалоговом окне.
- в поле» системные переменные » найдите путь и отредактируйте его, чтобы включить C:\Program Files\nodejs . Убедитесь, что он отделен от любых других путей с помощью ; .
вы придется перезапустить все открытые в настоящее время командные подсказки, прежде чем он вступит в силу.
npm config get prefix
и просто в качестве будущей ссылки, это путь, который я добавил В Windows 10:
зайдите в Панель управления -> Система -> Дополнительные параметры системы переменные среды.
отсюда найдите переменную path, перейдите в конец строки и вставьте «C:\Program Files\nodejs\node_modules\npm\bin «(измените путь к каталогу, в котором вы его установили, например, если вы специально установили его в любом месте, измените его)
Я использую Windows 10 — 64 бита, поэтому я бегу. Команды:
- NVM arch 64 (чтобы сделать по умолчанию 64-разрядный исполняемый файл)
- список nvm (чтобы перечислить все доступные версии узлов)
- nvm установить 8.0.0 (для загрузки узла версии 8.0.0-вы можете выбрать любой)
- nvm использовать 8.0.0 (чтобы использовать этот конкретный версия)
в моем случае мне пришлось просто переключиться на версию 8.5.0 а затем снова переключиться на 8.0.0 и это было исправлено. По-видимому, NVM устанавливает переменные пути всякий раз, когда вы делаете этот переключатель.
Я использовал командлет и перейдите к пути, на который вы хотите переключить файлы npm. Введите npm root-g чтобы узнать, на какой текущий путь установлен ваш npm. Следующее использование npm config set prefix и ваш путь npm будет изменен на любой каталог, в котором вы сейчас находитесь.
попробуйте этот чувак, если вы используете Windows:
1.) Поиск переменных среды в поле поиска меню Пуск.
2.) Нажмите на него, а затем перейдите к Environment Variables.
3.) Нажмите путь, нажмите кнопку Edit
4.) Нажмите новая и попробуйте скопировать и вставить это: C:\Program файлы\nodejs\node_modules\npm\bin
если вы получили сообщение об ошибке. Число 4.) Нажмите кнопку Создать, а затем просмотрите bin папка
- вы также можете посетить этой ссылке для получения дополнительной информации.
Это сработало для меня: 1. npm root-g (чтобы увидеть текущий npm установлен) 2. npm config set prefix (изменить путь)
У меня была эта проблема на 2 компьютерах в моем доме, используя Windows 10 каждый. Проблема началась, когда мне пришлось изменить несколько переменных среды для проектов, над которыми я работал в Visual studio 2017 и т. д. Через несколько месяцев, вернувшись к использованию node js и npm, у меня снова возникла эта проблема, и не помогли решения выше. Я видел комментарий Шона к решению Яра, и я смешал оба решения: 1) в окне переменные среды у меня была одна дополнительная переменная, которая содержала это значение: %APPDATA%\npm. Я удалил его, и проблема исчезла!
NPM package ‘bin’ script for Windows
Cucumber.js is supplying a command-line «binary» which is a simple .js file containing a shebang instruction:
The binary is specified in package.json with the «bin» configuration key:
This all works well on POSIX systems. Someone reported an issue when running Cucumber.js on Windows.
Basically, the .js file seems to be executed through the JScript interpreter of Windows (not Node.js) and it throws a syntax error because of the shebang instruction.
My question is: what is the recommended way of setting up a «binary» script that works on both UNIX and Windows systems?
3 Answers 3
Windows ignores the shebang line #!/usr/bin/env node and will execute it according to the .js file association. Be explicit about calling your script with node
ps. Pedantry: shebangs aren’t in the POSIX standard but they are supported by most *nix system.
If you package your project for Npm, use the ‘bin’ field in package.json. Then on Windows, Npm will install a .cmd wrapper along side your script so users can execute it from the command-line
For npm to create the shim right, the script must have the shebang line #!/usr/bin/env node
your «bin» should be «cucumber» npm will create a «cucumber» or «cucumber.cmd» file pointing to «node %SCRIPTNAME%». the former being for posix environments, the latter being for windows use. If you want the «js» to be part of the executable name. you should use a hyphon instead. «cucumber-js» . Having a .js file will come before the .js.cmd in your case causing the WScript interpreter to run it as a JScript file, not a node script.
I would suggest looking at coffee-script’s package.json for a good example.
I managed to figure out a solution to a similar issue.
My original plan was to have only one large .js file, for both the API and CLI (the reason is because I didn’t know how to share variables between two files at the time). And when everything was built, I tried to add the #!/usr/bin/env node shebang to my file. However that didn’t stop Windows Script Host from giving an error.
What I ended up doing was coming up with an idea of a «variable bridge» that allowed variables to be read and set using getVar and setVar . This made me have to extract the CLI code from the API code and add some imports to the variable bridge.
In the CLI file, I added the shebang, and modified the package.json of my project to have:
Here are a few small notes that I think might help if Windows Script Host is still giving an error (I applied all of them so I’m not sure which one helped):
Using only LF line endings seemed to help.
It seems that ./bin is the preferred directory for compiled files. I did try ./dist but it didn’t work for me.
An empty line after the shebang may be needed:
Как настроить переменные окружения (NODE_PATH)?
Постоянно сталкиваюсь с проблемой NODE_PATH
К примеру, в package.json прописано
Сборка спотыкается на NODE_PATH
«NODE_PATH не является внутренней или внешней командой, исполняемой программой. «
Как я понимаю проблема в том, что сборка писалась на UNIX системах, а у меня Виндоус.
Нужно задать переменные окружения
Вроде задал
Но не помогает.
- Вопрос задан более трёх лет назад
- 15151 просмотр
Каждое значение в scripts — это, по сути, скрипт операционной системы. Все верно, написаны они для *nix, и под виндой работать не будут даже при всех переменных окружения, потому что конструкция типа NODE_PATH=$NODE_PATH:./shared не является валидной для виндового интерпретатора командной строки. Надо исправить на что-то такое: SET NODE_PATH=%NODE_PATH%;.\shared . Скорее всего, путь к папке shared должен быть абсолютным.
Команду build надо поменять как-то так:
Другие способы:
1) сделать форк, написать на JS кросс-платформенные скрипты, которые запускают нужные вещи с нужными параметрами, положить их в папку bin проекта и послать pull-request
2) одуматься и перейти на линукс.
Node npm windows file paths are too long to install packages
Situation
I want to use gulp and related front-end tool chains in Windows-hosted development environments. I’m hitting a wall trying to use gulp plug-ins like Browser-Sync, because the node_modules folder graph fans out making the windows file paths too long to copy the files. I’d like a pragmatic approach for handling this problem right now on Windows, irrespective of what the Node community may or may not provide to improve npm usability on the Windows in the future.
2 Questions
Is there an npm workflow for Windows that just works the way it was intended? «run the command and the files install» (e.g. comparable to npm on OSX, npm on Linux, ruby gems or even nuget) I don’t want to fiddle with a bunch of manual file edits, symlinks, etc. every time I use npm on Windows.
Is there a well-documented, stable Cygwin workflow for npm and node execution to workaround the Windows API file path limits?
Gory details listed below.
General Problem
- Running npm install from a standard Windows command prompt fails on deeply nested node_modules hierarchies.
- Per Joyent’s github repo thread, this is an acknowledged issue with no palatable workarounds for developers in Windows-centric environments. (Really?)
- NT Kernel supports file path lengths up to 32,767 characters.
- Windows API’s MAXPATH is limited to 260 characters.
- Windows API handles file operations for all major Windows shells and whatnot including: Explorer, CMD, Powershell,MYSgit bash, etc. (MS really? How long has NTFS been around?)
- Cygwin supports long file paths, but npm.cmd doesn’t work out-of-box due to crlf formatting. I tried the DOS2Unix transform on npm to get it working with Cygwin, but there seem to be other issues with this.
My Current Hack
- Create an «n» folder as a staging area on the root of C:\, because this shortens my folder path.
- Run npm inside the «n» folder to install modules for whatever I need.
- Fire up Cygwin and use cp to copy the node_modules folder into a destination project.
- Rinse and repeat when dependencies change or when I need to spin up a new project.
Other Unpalatable Workarounds
Symbolic Links can be used to shorten file paths, but these are kludgy hacks. As the npm ecosystem grows, nested dependency chains will become too long and this workaround become unusable.
Global npm install location on windows?
I’m not 100% sure, but I believe I installed node v5 from the windows installer on both my home and office PCs.
On my home PC global installs happen under %APPDATA%:
while on my office PC, they go under program files:
I need to provide the full path to a number of these global tools to PyCharm’s file watcher, and since the project file i shared it would make sense to not have global resources under a user folder.
Why would the global installs end up in different folders, and how can I force them to a location that is common to all team members?
4 Answers 4
- Local install (default): puts stuff in ./node_modules of the current package root.
- Global install (with -g): puts stuff in /usr/local or wherever node is installed.
- Install it locally if you’re going to require() it.
- Install it globally if you’re going to run it on the command line. -> If you need both, then install it in both places, or use npm link.
prefix Configuration
The prefix config defaults to the location where node is installed. On most systems, this is /usr/local . On windows, this is the exact location of the node.exe binary.
The docs might be a little outdated, but they explain why global installs can end up in different directories:
Based on the other answers, it may seem like the override is now the default location on Windows, and that I may have installed my office version prior to this override being implemented.
This also suggests a solution for getting all team members to have globals stored in the same absolute path relative to their PC, i.e. (run as Administrator):
open a new cmd.exe window and reinstall all global packages.
Explanation (by lineno.):
- Create a folder in a sensible location to hold the globals (Microsoft is adamant that you shouldn’t write to ProgramFiles, so %PROGRAMDATA% seems like the next logical place.
- The directory needs to be on the path, so use setx .. /M to set the system path (under HKEY_LOCAL_MACHINE). This is what requires you to run this in a shell with administrator permissions.
- Tell npm to use this new path. (Note: folder isn’t visible in %PATH% in this shell, so you must open a new window).