JavaScript · Technical

NPM Fix

 

Now, we’re experiencing a problem with npmjs registries at Egypt, um not sure if this is a regional problem, but I don’t think so, some may have not these problems, some say it’s ISP problems, nothing clear yet …

commands like

npm i grunt -g

takes loooot of time, and 99% will fail.

What’re the solutions?

  1. Find a free and working mirror. (couldn’t find a one, walked into multiple directions, but none of them worked)
  2. Install npm-onSite, which is not free.
  3. Make your own workaround, which I went for.

 

Here’s how I did npm work again:

First, this is the normal flow when you use npm.

npm1

on our development server, which is located on Azure in Europe, I tried first to make sure that npm is working fine,  and yes, verified.

I thought about using this server as a proxy. and here’s how:

0) Prerequisites 

  • A VM hosted somewhere out of Egypt
  • Node and npm installed on this remote machine
  • rsync (It’s probably installed by default)

1) Prepare your server

  • ssh it
    ssh <user>@<ip>
  • add your public ssh key to the authorized users
    you’re good enough to Google it, um sure.
  • make a directory that will only act as an npm registry for you
    cd ~
    mkdir remote-node-modules
    cd remote-node-modules
    npm init
    # go through npm initialization wizard
  • make a simple shell script that we can execute remotely
    cd ~
    vim npm.sh

    n2 Here’s the code

  • grant npm.sh executable permission
    chmod +x npm.sh
  • now your server is ready!

 

2) Setup your development/local machine

  • export two environment variables to use while communicating to your remote server
    vim ~/.bashrc # or sudo gedit ~/.bashrc
    # scroll down to the end of file, then paste the following
    export NPM_REMOTE=<your remote server ip>
    export NPM_REMOTE_USER=<user that's allowed now to ssh remote server>
  • add npm.sh  to your project
    cd /path/to/your/project
    vim npm.sh
    


    n1
    Here’s the code

  • grant npm.sh executable
  • We’re good to go!

Sample usage

./npm.sh -v
./npm.sh install lodash --save

Better…

Rename npm.sh to npm for better usability

mv npm.sh npm
# Now you can use it as ./npm -v

 

Here’s how the new flow will be

npm2

Pros: 

  1. You don’t need to manually do any more steps than you before, you don’t need to ssh or sync manually.
  2. You keep exactly the same project structure as before, npm_modules ignored, and managed through package.json
  3.  You can integrate back directly with npm at anytime, without any changes.
  4. This doesn’t work as a black box, you get instant feedback, just like if you run npm on your local machine.

 

Cons:

  1. You can’t update package.json from inside the project, it’ll get overwritten when you do ./npm install X

 

I really hope you find this post useful in one way or another …

I have a WOOOORKING npm!

2 thoughts on “NPM Fix

Leave a comment