且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

安装Node.js后,npm失败

更新时间:2023-12-04 11:27:22

解决方案不需要任何重新启动的应用程序是将完整路径传递到 nodejs 程序文件夹中的 npm 命令。这样你就不需要依赖于Windows和它的环境变量 - 这是一条直接的路线。请注意您是否正在安装32位或64位版本的Node.js,并确保查看相应的文件夹...

  C:\Program Files\\\
odejs\\\
pm
C:\Program文件(x86)\\\
odejs\\\
pm


I'm working on an installer which automates the installation of Node.js, extracts a node application to a folder, and then installs it via npm install. However, the installer always needs to be run twice in order for npm to work. This is installing onto Windows.

During the lifetime of my installer app...

  • If Node.js wasn't already installed, it gets installed
  • In the same process, steps later, npm install is executed
  • If Node.js didn't already exist before installer started, it fails saying npm is not a valid command
  • If Node.js was already installed when installer started, it succeeds

What I'm assuming is that the installation of Node.js creates new environment variables, but my process has not yet obtained these new variables - until the process is restarted. Then, the second time it can see those variables. Otherwise, within the same process, it cannot find npm because it cannot see the new environment variables. At least this is what I've narrowed the issue down to and is the only explanation why I always have to run my installer twice.

Background: The installer is created using Inno Setup (Unicode). I created an application in Delphi to display the user an interface while the installation is being done, as a majority of the original installer just displayed a blank non-responsive page saying "Preparing to install...". This Delphi application performs the actual install process inside of a thread, and that thread uses events to update a grid visible to the user. This event-driven thread reports the progress of each installation step back to the main form, and displays a responsive user interface showing each step of the install process and its status. This application then returns back an exit code to the installer for further handling.

If it weren't for requiring the wait for each sub-process and obtaining their exit codes, this wouldn't be an issue. But since I need to do that, Windows naturally passes the cached environment variables to each sub-process, still rendering them useless.

How can I force my application to see the new environment variables which have been added since the process started?

The solution without requiring any restart of your application is to pass the full path to the npm command in the nodejs program files folder. That way you won't need to rely on Windows and its environment variables - it's a direct route. Keep note of whether you're installing the 32bit or 64bit editions of Node.js, and make sure you look in the appropriate folder...

C:\Program Files\nodejs\npm
C:\Program Files (x86)\nodejs\npm