How do you set up npm (node package manager) without root access? - javascript

Setting npm up as the root user is straighforward and workds. Except you have to run npm commands as root (not recommended). So I thought I'd try setting it up as a non-root user.
According to npm documentation, a non-root user without root access can set up npm by:
creating a .npmrc file with root, binroot, and manroot pointing to folders that the user owns.
Then running the install script.
OK. Install was fine.
But node can't see the packages provided by npm.
So how do I make node aware of the packages provided by npm? (I didn't have to do anything when I previously installed npm as root).
I can set require.paths within node, or set the NODE_PATH environment variable, but to what?
Thanks.

This worked for me:
Make a ~/.node folder
mkdir ~/.node
Edit ~/.npmrc and add the line
prefix = ~/.node
Edit your ~/.profile or ~/.bash_profile and add these lines
PATH="$HOME/.node/bin:$PATH"
NODE_PATH="$HOME/.node/lib/node_modules:$NODE_PATH"
Now I can do things like npm -g install http-server and it will install to ~/.node without root. With this in place, when I then type http-server, it runs.

Through a little exploration, it seems you can either:
set your NODE_PATH to whatever npm's root directory is, or
while in node, invoke require.paths.push('path_to_npm_root')

Related

How to install Puppeteer as offline

My host machine's firewall will not allow connecting to the internet.
So npm install will not work there.
npm ERR! network request to https://registry.npmjs.org/Puppeteer failed
So how can I install Puppeteer in this machine? Is there any standalone installer available?
I do the following whenever I'm on road or don't have internet access but want to use some node_modules somewhere afar.
Two ways to deal with this:
Create the project and install all dependencies while you have the internet access, use it whenever you want.
Install just the specific dependencies and copy the node_modules and package.json around.
I will discuss the second because both options are basically same.
First, find a computer with internet access. And then create a blank nodeJS project just for puppeteer. Copy the whole node_modules folder for future usage, not just puppeteer folder. Note that it will never get updated and the version is always fixed. If you want to update it, you need to do similar steps again.
Here is the steps,
➜ mkdir puppeteer-copy
➜ cd puppeteer-copy
➜ yarn add puppeteer
On the package.json file, you will see a puppeteer listed as dependency, make sure you have this on your program when using this copied package. You can copy just that line if you want.
➜ ls
node_modules package.json yarn.lock
➜ cat package.json
{
"dependencies": {
"puppeteer": "^2.0.0"
}
}
The reason you need the whole node_modules folder is because of some dependencies puppeteer uses,
➜ node_modules ls
agent-base es6-promisify minimatch puppeteer
async-limiter extract-zip minimist readable-stream
balanced-match fd-slicer mkdirp rimraf
brace-expansion fs.realpath ms safe-buffer
buffer-from glob once string_decoder
concat-map https-proxy-agent path-is-absolute typedarray
concat-stream inflight pend util-deprecate
core-util-is inherits process-nextick-args wrappy
debug isarray progress ws
es6-promise mime proxy-from-env yauzl
Maybe go in a computer that does have internet access, install puppeteer inside of an npm project.(npm init -y && npm i puppeteer) then search through the node_modules folder that gets created and copy the puppeteer folder inside it. Paste that into a flash drive, connect it to computer with no internet and drag and drop into your project into the node_modules folder. I haven't tried if this works but this would be my first approach. I'm curious as to what you are trying to accomplish with puppeteer if you have no internet though...

'vue' is not recognized as an internal or external command

everything was installed correctly. but whenever I try to create project, it says "'vue' is not recognized as an internal or external command". I installed and re-installed but didn't work. npm was also added to environmental variable path.
C:\Users\touha\Desktop>npm list -g --depth=0
C:\Users\touha\.npm-packages
`-- #vue/cli#3.8.2
C:\Users\touha\Desktop>vue ui
'vue' is not recognized as an internal or external command,
operable program or batch file.
C:\Users\touha\Desktop>
Locate vue.cmd and add its location to your PATH
It is added to package manager(npm or yarn) installation. So you may find it at following locations
YARN
C:\Users{YourAccount}\AppData\Local\Yarn\bin
NPM
C:\Users{YourAccount}\AppData\Roaming\npm
just open PowerShell and run: npm install -g #vue/cli
Addition: If setting the path variable and reinstalling #vue/cli does not work, using the node.js command prompt instead might solve the issue.
It seems vue isn't been installed globally for some reasons.
This is the step I followed to solve mine:
Firstly, create your desired project folder (say "Vue Project"). This is where you want to create a vue project.
Then create a "node_modules" folder in the Vue Project folder
Then go to your system npm folder C:\Users{YourAccount}\AppData\Roaming\npm
You will see three different "vue" files. Copy them and paste in the Vue Project Folder you created.
Go back to C:\Users{YourAccount}\AppData\Roaming\npm and enter the node_modules folder. You'll see a "#vue" folder. Copy this, and paste it in the node_modules folder you created in the Vue Project Folder.
You can now head back to the CLI and create your project using "vue create my-vue-project" where my-vue-project is your desired vue project name.
You can try this way it worked for me
go to the location of your yarn or npm mine is C:\Users\TED\AppData\Local\Yarn\bin for Yarn
C:\Users\TED\AppData\Local\Npm\bin for Npm users
TED will be replaced by your user name
then copy and add it to your system environment variable
Note in case you don't find AppData make sure you have view hidden file checked
I am using Yarn to install #vue/cli.
The way I solve it is via the following steps
Locate your global installed vue.cmd location
Add the vue.cmd directory into System variable Env. For myself, the path is C:\Users{MyAccount}\AppData\Local\Yarn\.bin
what worked for me:
In a powershell :
npm install vue
npm install -g #vue/cli
C:\Users\{USER}\AppData\Roaming\npm\vue.cmd create {NAME}
if you got this error most probably chance package not installed completely
check-in C:\Users\dev\AppData\Roaming\npm
if you had not found the package under this folder then re-run your command
Run command prompt as administrator
Run setx /M path "%path%;%appdata%\npm
Restart the command prompt
Now create the Vue project

How to make a nodejs script be a CLI tool in linux?

I made a javascript file mytool.js, it has some dependencies (in package.json).
Now I can execute typing in
~/mynodes/mytool $ node mytool
But if I change the working directory I can't use this command anymore because previously it was run locally.
What I want to achieve is to be able to just type :
~$ mytool
(wherever I am in my system's filesystem and without typing node before).
Should I install it manually ?
If yes, where is the common location to install a personal nodejs script in a unix-like system ?
Or is there a npm-like command to install a personal script system
wide ?
When you add a "bin" key in your package.json:
"bin": {
"mytool": "mytool.js"
},
then you will be able to install your script with npm install -g and it will be automatically added where it should be (to a place where other globally installed cli tools are installed, which should be in your PATH).
You can see this simple project as an example:
https://github.com/rsp/node-websocket-vs-socket.io
It was created as an example for this answer but it does what you need:
it has a single script to run
it has external dependencies
it can be installed globally
it can be run from any place with a single command
Note that you don't need to publish your script to npm to be able to install it - though you can do it, or you can also install projects directly from GitHub (including private repos) - but you can also install a module that you have in your local directory or a tarball:
npm install -g module-on-npm
npm install -g user/repo-on-github
npm install -g /your/local/directory
npm install -g /your/local/tarball.tgz
For more options, see:
https://docs.npmjs.com/cli/install
Also keep in mind that for your program to be able to be executed from anywhere, you need to use paths relative to __dirname or __filename if you need to access your own files relative to your code. See:
https://nodejs.org/api/globals.html#globals_dirname
Put a shebang line at the top of the script (e.g. #!/usr/bin/env node).
Put the script in a directory in your $PATH
Give it executable permission (e.g. chmod +x /usr/local/bin/example.js)
First option:
You can run your file globally by putting on the first line of the file : #!/usr/bin/env node, copying it to /usr/local/bin and make it executable: sudo chmod +x /usr/local/bin/yourfile.js and then you can call it from where you want with yourfile.js
Second option:
Make your local file executable and create an executable bash script which calls your local file and put it in /usr/local/bin and then call the bashfile globally.

Yarn global command not working

I'm working with Yarn v0.16.1. If I understand correctly (according to the documentation), yarn global add <package> should be the equivalent of npm install -g <package>. However, when I run the example in the docs (with create-react-app), the command runs successfully but create-react-app is then not available from the command line. Here's the output:
$ yarn global add create-react-app
$ yarn global v0.16.1
[1/4] 🔍 Resolving packages...
[2/4] 🚚 Fetching packages...
[3/4] 🔗 Linking dependencies...
[4/4] 📃 Building fresh packages...
success Installed create-react-app#0.6.0 with binaries:
- create-react-app
✨ Done in 3.22s.
$ create-react-app --help
-bash: create-react-app: command not found
Doing a global install with npm has the expected result, and everything works. What am I missing with yarn?
You should add export PATH="$PATH:$(yarn global bin)" to your ~/.bash_profile or whatever you use. It would solve the issue.
Depending on how you installed it, Yarn's global folder varies for some reason. You can follow this issue here.
Update Dec 2018
Just updating the path didn't work for me. I had to also set the yarn prefix.
Ubuntu 18.04.1 LTS (bionic)
yarn 1.12.3
npm v3.5.2
node v8.10.0
zsh 5.4.2
Steps
Confirm your global bin path
yarn global bin
I got: /home/username/.yarn/bin
set yarn prefix:
make sure your yarn prefix is the parent directory of your bin directory. You can confirm by running
yarn config get prefix
when I ran this, my prefix was empty, so I set it:
yarn config set prefix ~/.yarn
add the following to ~/.bash_profile or ~/.bashrc
export PATH="$PATH:`yarn global bin`"
for zsh users, be sure to add this line to ~/.zshrc
restart your shell or start a new one
bash -l or zsh
In my case yarn global bin wasn't working.
Try a brew reinstall yarn if that's how you installed yarn
👍🏻
Ran into this issue but on a Windows system. All I had to do was add the yarn global bin to the PATH variable.
setx path "%path%;c:\users\YOURUSERNAME\appdata\local\yarn\bin"
Remember to change YOURUSERNAME to your account username.
You can check where your global bin is by running
yarn global bin
And please don't forget to restart the CMD window that you're working on.
Happy coding!
! WARNING !
When executing the command that %path%; in front of your yarn directory is very important. If you don't type it you will definitely replace all your system environment variables.
Option 2
Safer option would be would be to just go to System Properties > Advanced > Environment Variables > select PATH the click Edit > then append and not replace with ;c:\users\YOURUSERNAME\appdata\local\yarn\bin
For macOS, you just need one step,
export PATH=~/.yarn/bin:$PATH
To reinstall run below.
brew install -g yarn
// Note:(updating homebrew) for Mac users.
brew reinstall yarn
// (if yarn is still not found)
Here's the process I used on Mac OSX El Capitan.
Try to install yarn (I used the Curl command) if you have it already. This will bring up if its already installed and will give you the current directory where it exists.
Like this:
curl -o- -L https://yarnpkg.com/install.sh | bash
It will display something like this:
Installing Yarn!
> /Users/{Your Username}/.yarn already exists, possibly from a past Yarn install.
> Remove it (rm -rf /Users/{Your Username}/.yarn) and run this script again.
Do not remove it. Move on to step 2.
Copy the directory listed above. Open your profile. I'm using zsh. So mine was ~/.zshrc. You can find yours and more info here.
Copy the following (replacing your directory and username details as necessary, the one you got from the installation error message).
alias yarn="/Users/{Your Username}/.yarn/bin/yarn"
Try to run yarn version to check if its working. If it is, you should see a version number displayed in your terminal.
That's it, and what worked for me.
AndrewD gave a great answer, but for those on Windows it's a bit different, especially step 3.
Please do not use the command setx as #Thapedict said.
It will remove all your previous paths you had and replace it with only the given directory.
If you want to use setx, I think there might be a flag to make it append the existing path variables, but I don't know which one. Using only setx will not append to it.
I would just do System Properties > Advanced > Environment Variables > Edit Path > New > c:\users\YOURUSERNAME\appdata\local\yarn\bin
to make sure you don't remove your previous variables.
export PATH="$PATH:$(yarn global bin)"
On Ubuntu, I fixed by installing the package like this:
sudo yarn global add <package> --prefix /usr/local
When switching from bash to zsh, I got the same error, it worked for me:
in your .zshrc
# NVM Stuff
export NVM_DIR="$HOME/.nvm"
. "$(brew --prefix nvm)/nvm.sh"
# YVM Stuff
export YVM_DIR="$HOME/.yvm"
. "$(brew --prefix yvm)/yvm.sh"
As I understand it, my mistake arose due to the lack of access to version managers
I faced a similar issue on Windows after installing Yarn then Vue Cli.
Packages were installed but not accessible.
The problem was that the directory where yarn packages are installed is not in PATH.
The default installation directory for Yarn packages in my case was
C:\Users\USERNAME\AppData\Local\Yarn
So make sure to add this directory to path.
Putting this answer so that hopefully it can come in google and help others.
expo command not found after using
yarn global add expo-cli don't work in ubuntu 20.04
It's no longer necessary to modify your path for yarn
Newer versions of yarn include yarn create and yarn exec
In the case of create-react-app you can run yarn create react-app see this blog post https://classic.yarnpkg.com/blog/2017/05/12/introducing-yarn/
To run a non-creating package like serve, you can still run it without modifying your path! After installing it with yarn global add serve try this: yarn exec serve

How to verify an object instance? instanceof and ....prototype.isPrototypeOf(...) are not reliable [duplicate]

Whenever I make projects, I have to download all dependencies of node modules. Without copying the node_modules, Is there anyway to share the central node_modules in multiple projects?
like the followings, I have to run many commands every time..
npm install gulp-usemin
npm install gulp-wrap
npm install gulp-connect
npm install gulp-watch
npm install gulp-minify-css
npm install gulp-uglify
npm install gulp-concat
npm install gulp-less
npm install gulp-rename
npm install gulp-minify-html
You absolutely can share a node_modules directory amongst projects.
From node's documentation:
If the module identifier passed to require() is not a native module,
and does not begin with '/', '../', or './', then node starts at the
parent directory of the current module, and adds /node_modules, and
attempts to load the module from that location.
If it is not found there, then it moves to the parent directory, and
so on, until the root of the file system is reached.
For example, if the file at '/home/ry/projects/foo.js' called
require('bar.js'), then node would look in the following locations, in
this order:
/home/ry/projects/node_modules/bar.js /home/ry/node_modules/bar.js
/home/node_modules/bar.js /node_modules/bar.js
So just put a node_modules folder inside your projects directory and put in whatever modules you want. Just require them like normal. When node doesn't find a node_modules directory in your project folder, it will check the parent folder automatically. So make your directory structure like this:
-myProjects
--node_modules
--myproject1
---sub-project
--myproject2
So like this, even your sub-project's dependencies can draw on your main node_modules repository.
One drawback to doing it this way is you will have to build out your package.json file manually (unless someone knows a way to automate this with grunt or something). When you install your packages and add the --save arg to an npm install command it automatically appends it to the dependencies section or your package.json, which is convenient.
Try pnpm instead of npm.
pnpm uses hard links and symlinks to save one version of a module only ever once on a disk.
If you have npm installed, you can install in your terminal with:
npm install -g pnpm
To update your existing installations (and sub-directories) use:
pnpm recursive install
Or use the shorthand command (leave off -r if you need to target only one directory)
pnpm -r i
One helpful note: You may find some rare packages don't have all their dependencies defined. They might rely on the flat node_modules file directory structure of npm or yarn installs. If you run into issues of missing dependencies, use this command to hoist all the sub dependencies into a flat-file structure:
pnpm install --shamefully-hoist
It's best to avoid using the --shamefully-hoist flag as it defeats the purpose of using pnpm in the first place, so try using the command pnpm i your-missing-package first (See pnpm FAQ).
I found a trick, just take a look at the Symbolic Links (symlinks) on Windows or Linux, it is working just like shortcuts but more powerful.
Simply you need to make a Junction for your node_modules folder anywhere you want. The junction is nothing but a short cut to your original node_modules folder. Create it inside your project folder where the actual node_modules would have been created if used npm install.
To achieve this you need at least one node_modules real folder then make a Junction to it in the other projects.
On Windows, you can either use the Command Prompt, or use an application. Using the Command Prompt gives you a bit more control, using an application is easier I suggest Link Shell Extension.
Main directory should look like this
node_modules
Project 1
Project 2
Project 3
Project 4
just open the file Project 1/.angular-cli.json
change the schema
"$schema": "./node_modules/#angular/cli/lib/config/schema.json",
to
"$schema": "./../node_modules/#angular/cli/lib/config/schema.json"
and don't forget to create node_modules empty folder inside your project directory
See also npm v7.0.0's support for workspaces
RFC
https://github.com/npm/rfcs/blob/latest/implemented/0026-workspaces.md
Documentation
https://docs.npmjs.com/cli/v7/using-npm/workspaces
By looking at some articles it seems that Lerna
is a good tool for managing multiple projects inside a single directory (monorepo). It supports modules sharing without duplicating the entire packages in every folder and commands to install them in multiple projects.
Javascript monorepos
Monorepos by example
Building large scale apps in a monorepo
pnpm is also a simple and efficient tool, which doesn't duplicate those modules which are already installed for other projects.
Let's assume that having a single node_modules it should contain all the packages for all applications. thus your apps will also share most of the unique package.json entries (just the name should change)
my idea would be to have a single root and multiple src level as below
root\package.json
root\node_modules
root\\..
root\app1\src\\..
root\app2\src\\..
the only issue you might face would be having a backup of json (or tsconfig) for any app and restore them when you work on it or setup your startup scripts to serve any app

Categories

Resources