Меню

Npm ошибка при установке пакетов

I’m trying to install some node packages through npm, but it won’t go.
I’ve already tried to install/unistall/update node, but nothing seems to work.

I’m using ubuntu 12.04 — Here is how i’m trying to install packages:

npm install underscore

npm http GET http://registry.npmjs.org/underscore
npm http 404 http://registry.npmjs.org/underscore
npm ERR! registry error parsing json
npm ERR! SyntaxError: Unexpected token <
npm ERR! <html>
npm ERR!   <head>
npm ERR!     <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
npm ERR!     <script type="text/javascript" language="JavaScript" src="http://img.sedoparking.com/registrar/dopark.js"></script>
npm ERR!   </head>
npm ERR!   <body style="display: none;">
npm ERR!     <script type="text/javascript">
npm ERR! var reg = 'sedonewreg';
npm ERR! document.write( '<scr'+'ipt type="text/javascript" language="JavaScript"' + 'src="http://sedoparking.com/' + window.location.host + '/' + reg + '/park.js">' + '</scr' + 'ipt>' );
npm ERR!     </script>
npm ERR!  </body>
npm ERR! </html>
npm ERR! 
npm ERR!     at Object.parse (native)
npm ERR!     at RegClient.<anonymous> (/home/smanastirliu/local/lib/node_modules/npm/node_modules/npm-registry-client/lib/request.js:235:23)
npm ERR!     at Request.self.callback (/home/smanastirliu/local/lib/node_modules/npm/node_modules/request/index.js:142:22)
npm ERR!     at Request.EventEmitter.emit (events.js:98:17)
npm ERR!     at Request.<anonymous> (/home/smanastirliu/local/lib/node_modules/npm/node_modules/request/index.js:856:14)
npm ERR!     at Request.EventEmitter.emit (events.js:117:20)
npm ERR!     at IncomingMessage.<anonymous> (/home/smanastirliu/local/lib/node_modules/npm/node_modules/request/index.js:808:12)
npm ERR!     at IncomingMessage.EventEmitter.emit (events.js:117:20)
npm ERR!     at _stream_readable.js:895:16
npm ERR!     at process._tickCallback (node.js:415:13)
npm ERR! If you need help, you may report this log at:
npm ERR!     <http://github.com/isaacs/npm/issues>
npm ERR! or email it to:
npm ERR!     <npm-@googlegroups.com>

npm ERR! System Linux 3.5.0-27-generic
npm ERR! command "/home/smanastirliu/local/bin/node" "/home/smanastirliu/local/bin/npm" "install" "underscore"
npm ERR! cwd /home/smanastirliu
npm ERR! node -v v0.10.5
npm ERR! npm -v 1.2.18
npm ERR! type unexpected_token
npm ERR! Error: EACCES, open 'npm-debug.log'
npm ERR!  { [Error: EACCES, open 'npm-debug.log'] errno: 3, code: 'EACCES', path: 'npm-debug.log' }
npm ERR! 
npm ERR! Please try running this command again as root/Administrator.

npm ERR! System Linux 3.5.0-27-generic
npm ERR! command "/home/smanastirliu/local/bin/node" "/home/smanastirliu/local/bin/npm" "install" "underscore"
npm ERR! cwd /home/smanastirliu
npm ERR! node -v v0.10.5
npm ERR! npm -v 1.2.18
npm ERR! path npm-debug.log
npm ERR! code EACCES
npm ERR! errno 3
npm ERR! stack Error: EACCES, open 'npm-debug.log'
npm ERR! 
npm ERR! Additional logging details can be found in:
npm ERR!     /home/smanastirliu/npm-debug.log
npm ERR! not ok code 0
smanastirliu@sviluppo69:~$ sudo npm install underscore
[sudo] password for smanastirliu: 
npm http GET http://registry.npmjs.org/underscore
npm http 404 http://registry.npmjs.org/underscore
npm ERR! registry error parsing json
npm ERR! SyntaxError: Unexpected token <
npm ERR! <html>
npm ERR!   <head>
npm ERR!     <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
npm ERR!     <script type="text/javascript" language="JavaScript" src="http://img.sedoparking.com/registrar/dopark.js"></script>
npm ERR!   </head>
npm ERR!   <body style="display: none;">
npm ERR!     <script type="text/javascript">
npm ERR! var reg = 'sedonewreg';
npm ERR! document.write( '<scr'+'ipt type="text/javascript" language="JavaScript"' + 'src="http://sedoparking.com/' + window.location.host + '/' + reg + '/park.js">' + '</scr' + 'ipt>' );
npm ERR!     </script>
npm ERR!  </body>
npm ERR! </html>
npm ERR! 
npm ERR!     at Object.parse (native)
npm ERR!     at RegClient.<anonymous> (/home/smanastirliu/Scaricati/node-v0.10.5-linux-x86/lib/node_modules/npm/node_modules/npm-registry-client/lib/request.js:235:23)
npm ERR!     at Request.self.callback (/home/smanastirliu/Scaricati/node-v0.10.5-linux-x86/lib/node_modules/npm/node_modules/request/index.js:142:22)
npm ERR!     at Request.EventEmitter.emit (events.js:98:17)
npm ERR!     at Request.<anonymous> (/home/smanastirliu/Scaricati/node-v0.10.5-linux-x86/lib/node_modules/npm/node_modules/request/index.js:856:14)
npm ERR!     at Request.EventEmitter.emit (events.js:117:20)
npm ERR!     at IncomingMessage.<anonymous> (/home/smanastirliu/Scaricati/node-v0.10.5-linux-x86/lib/node_modules/npm/node_modules/request/index.js:808:12)
npm ERR!     at IncomingMessage.EventEmitter.emit (events.js:117:20)
npm ERR!     at _stream_readable.js:895:16
npm ERR!     at process._tickCallback (node.js:415:13)
npm ERR! If you need help, you may report this log at:
npm ERR!     <http://github.com/isaacs/npm/issues>
npm ERR! or email it to:
npm ERR!     <npm-@googlegroups.com>

npm ERR! System Linux 3.5.0-27-generic
npm ERR! command "/usr/local/bin/node" "/usr/local/bin/npm" "install" "underscore"
npm ERR! cwd /home/smanastirliu
npm ERR! node -v v0.10.5
npm ERR! npm -v 1.2.18
npm ERR! type unexpected_token
npm ERR! 
npm ERR! Additional logging details can be found in:
npm ERR!     /home/smanastirliu/npm-debug.log
npm ERR! not ok code 0

and here is the debug.log:

0 info it worked if it ends with ok
1 verbose cli [ '/usr/local/bin/node',
1 verbose cli   '/usr/local/bin/npm',
1 verbose cli   'install',
1 verbose cli   'underscore' ]
2 info using npm@1.2.18
3 info using node@v0.10.5
4 verbose node symlink /usr/local/bin/node
5 verbose read json /home/smanastirliu/package.json
6 verbose read json /home/smanastirliu/package.json
7 verbose cache add [ 'underscore', null ]
8 verbose cache add name=undefined spec="underscore" args=["underscore",null]
9 verbose parsed url { protocol: null,
9 verbose parsed url   slashes: null,
9 verbose parsed url   auth: null,
9 verbose parsed url   host: null,
9 verbose parsed url   port: null,
9 verbose parsed url   hostname: null,
9 verbose parsed url   hash: null,
9 verbose parsed url   search: null,
9 verbose parsed url   query: null,
9 verbose parsed url   pathname: 'underscore',
9 verbose parsed url   path: 'underscore',
9 verbose parsed url   href: 'underscore' }
10 silly lockFile 64bc6893-underscore underscore
11 verbose lock underscore /home/smanastirliu/.npm/64bc6893-underscore.lock
12 silly lockFile 64bc6893-underscore underscore
13 silly lockFile 64bc6893-underscore underscore
14 verbose addNamed [ 'underscore', '' ]
15 verbose addNamed [ null, '' ]
16 silly lockFile 7629b758-underscore underscore@
17 verbose lock underscore@ /home/smanastirliu/.npm/7629b758-underscore.lock
18 silly addNameRange { name: 'underscore', range: '', hasData: false }
19 verbose url raw underscore
20 verbose url resolving [ 'http://registry.npmjs.org/', './underscore' ]
21 verbose url resolved http://registry.npmjs.org/underscore
22 info trying registry request attempt 1 at 16:38:48
23 http GET http://registry.npmjs.org/underscore
24 http 404 http://registry.npmjs.org/underscore
25 verbose bad json <html>
25 verbose bad json   <head>
25 verbose bad json     <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
25 verbose bad json     <script type="text/javascript" language="JavaScript" src="http://img.sedoparking.com/registrar/dopark.js"></script>
25 verbose bad json   </head>
25 verbose bad json   <body style="display: none;">
25 verbose bad json     <script type="text/javascript">
25 verbose bad json var reg = 'sedonewreg';
25 verbose bad json document.write( '<scr'+'ipt type="text/javascript" language="JavaScript"' + 'src="http://sedoparking.com/' + window.location.host + '/' + reg + '/park.js">' + '</scr' + 'ipt>' );
25 verbose bad json     </script>
25 verbose bad json  </body>
25 verbose bad json </html>
26 error registry error parsing json
27 silly registry.get cb [ 404,
27 silly registry.get   { date: 'Mon, 29 Apr 2013 14:39:02 GMT',
27 silly registry.get     server: 'Apache',
27 silly registry.get     'content-length': '521',
27 silly registry.get     connection: 'close',
27 silly registry.get     'content-type': 'text/html; charset=UTF-8' } ]
28 silly lockFile 7629b758-underscore underscore@
29 silly lockFile 7629b758-underscore underscore@
30 error SyntaxError: Unexpected token <
30 error <html>
30 error   <head>
30 error     <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
30 error     <script type="text/javascript" language="JavaScript" src="http://img.sedoparking.com/registrar/dopark.js"></script>
30 error   </head>
30 error   <body style="display: none;">
30 error     <script type="text/javascript">
30 error var reg = 'sedonewreg';
30 error document.write( '<scr'+'ipt type="text/javascript" language="JavaScript"' + 'src="http://sedoparking.com/' + window.location.host + '/' + reg + '/park.js">' + '</scr' + 'ipt>' );
30 error     </script>
30 error  </body>
30 error </html>
30 error
30 error     at Object.parse (native)
30 error     at RegClient.<anonymous> (/home/smanastirliu/Scaricati/node-v0.10.5-linux-x86/lib/node_modules/npm/node_modules/npm-registry-client/lib/request.js:235:23)
30 error     at Request.self.callback (/home/smanastirliu/Scaricati/node-v0.10.5-linux-x86/lib/node_modules/npm/node_modules/request/index.js:142:22)
30 error     at Request.EventEmitter.emit (events.js:98:17)
30 error     at Request.<anonymous> (/home/smanastirliu/Scaricati/node-v0.10.5-linux-x86/lib/node_modules/npm/node_modules/request/index.js:856:14)
30 error     at Request.EventEmitter.emit (events.js:117:20)
30 error     at IncomingMessage.<anonymous> (/home/smanastirliu/Scaricati/node-v0.10.5-linux-x86/lib/node_modules/npm/node_modules/request/index.js:808:12)
30 error     at IncomingMessage.EventEmitter.emit (events.js:117:20)
30 error     at _stream_readable.js:895:16
30 error     at process._tickCallback (node.js:415:13)
31 error If you need help, you may report this log at:
31 error     <http://github.com/isaacs/npm/issues>
31 error or email it to:
31 error     <npm-@googlegroups.com>
32 error System Linux 3.5.0-27-generic
33 error command "/usr/local/bin/node" "/usr/local/bin/npm" "install" "underscore"
34 error cwd /home/smanastirliu
35 error node -v v0.10.5
36 error npm -v 1.2.18
37 error type unexpected_token
38 verbose exit [ 1, true ]

Another example with Karma:

sudo npm install karma
npm http GET http://registry.npmjs.org/karma
npm http 304 http://registry.npmjs.org/karma
npm http GET http://registry.npmjs.org/http-proxy
npm http GET http://registry.npmjs.org/glob
npm http GET http://registry.npmjs.org/minimatch
npm http GET http://registry.npmjs.org/optimist/0.3.5
npm http GET http://registry.npmjs.org/coffee-script
npm http GET http://registry.npmjs.org/rimraf
npm http GET http://registry.npmjs.org/xmlbuilder/0.4.2
npm http GET http://registry.npmjs.org/q
npm http GET http://registry.npmjs.org/LiveScript/1.0.1
npm http GET http://registry.npmjs.org/colors/0.6.0-1
npm http GET http://registry.npmjs.org/dateformat/1.0.2-1.2.3
npm http GET http://registry.npmjs.org/istanbul/0.1.22
npm http GET http://registry.npmjs.org/growly
npm http GET http://registry.npmjs.org/lodash
npm http GET http://registry.npmjs.org/pause/0.0.1
npm http GET http://registry.npmjs.org/mime
npm http GET http://registry.npmjs.org/log4js
npm http GET http://registry.npmjs.org/socket.io
npm http GET http://registry.npmjs.org/chokidar
npm http 304 http://registry.npmjs.org/minimatch
npm http 304 http://registry.npmjs.org/glob
npm http 304 http://registry.npmjs.org/optimist/0.3.5
npm http 304 http://registry.npmjs.org/coffee-script
npm http 304 http://registry.npmjs.org/xmlbuilder/0.4.2
npm http 304 http://registry.npmjs.org/rimraf
npm http 304 http://registry.npmjs.org/q
npm http 304 http://registry.npmjs.org/LiveScript/1.0.1
npm http 304 http://registry.npmjs.org/dateformat/1.0.2-1.2.3
npm http 304 http://registry.npmjs.org/growly
npm http 304 http://registry.npmjs.org/istanbul/0.1.22
npm http 304 http://registry.npmjs.org/colors/0.6.0-1
npm http 304 http://registry.npmjs.org/lodash
npm http 304 http://registry.npmjs.org/mime
npm http 304 http://registry.npmjs.org/pause/0.0.1
npm http 304 http://registry.npmjs.org/log4js
npm http 304 http://registry.npmjs.org/socket.io
npm http 304 http://registry.npmjs.org/chokidar
npm http 200 http://registry.npmjs.org/http-proxy
npm http GET http://registry.npmjs.org/http-proxy/-/http-proxy-0.10.2.tgz
npm http 200 http://registry.npmjs.org/http-proxy/-/http-proxy-0.10.2.tgz
npm http GET http://registry.npmjs.org/graceful-fs
npm http GET http://registry.npmjs.org/lru-cache
npm http GET http://registry.npmjs.org/sigmund
npm http GET http://registry.npmjs.org/graceful-fs
npm http GET http://registry.npmjs.org/inherits
npm http GET http://registry.npmjs.org/wordwrap
npm http GET http://registry.npmjs.org/base64id/0.1.0
npm http GET http://registry.npmjs.org/socket.io-client/0.9.11
npm http GET http://registry.npmjs.org/policyfile/0.0.4
npm http GET http://registry.npmjs.org/redis/0.7.3
npm http GET http://registry.npmjs.org/async/0.1.15
npm http GET http://registry.npmjs.org/dequeue/1.0.3
npm http GET http://registry.npmjs.org/prelude-ls
npm http GET http://registry.npmjs.org/semver
npm http GET http://registry.npmjs.org/readable-stream
npm http GET http://registry.npmjs.org/esprima
npm http GET http://registry.npmjs.org/escodegen
npm http GET http://registry.npmjs.org/handlebars
npm http GET http://registry.npmjs.org/mkdirp
npm http GET http://registry.npmjs.org/nopt
npm http GET http://registry.npmjs.org/fileset
npm http GET http://registry.npmjs.org/which
npm http GET http://registry.npmjs.org/async
npm http GET http://registry.npmjs.org/abbrev
npm http GET http://registry.npmjs.org/wordwrap
npm http 200 http://registry.npmjs.org/graceful-fs
npm http GET http://registry.npmjs.org/graceful-fs/-/graceful-fs-1.2.0.tgz
npm http 200 http://registry.npmjs.org/graceful-fs
npm http 200 http://registry.npmjs.org/inherits
npm http GET http://registry.npmjs.org/inherits/-/inherits-1.0.0.tgz
npm http GET http://registry.npmjs.org/pkginfo
npm http GET http://registry.npmjs.org/utile
npm http 200 http://registry.npmjs.org/base64id/0.1.0
npm http GET http://registry.npmjs.org/base64id/-/base64id-0.1.0.tgz
npm http 200 http://registry.npmjs.org/wordwrap
npm http GET http://registry.npmjs.org/wordwrap/-/wordwrap-0.0.2.tgz
npm http 200 http://registry.npmjs.org/lru-cache
npm http GET http://registry.npmjs.org/lru-cache/-/lru-cache-2.3.0.tgz
npm http 200 http://registry.npmjs.org/policyfile/0.0.4
npm http GET http://registry.npmjs.org/policyfile/-/policyfile-0.0.4.tgz
npm http 200 http://registry.npmjs.org/dequeue/1.0.3
npm http 200 http://registry.npmjs.org/async/0.1.15
npm http GET http://registry.npmjs.org/dequeue/-/dequeue-1.0.3.tgz
npm http GET http://registry.npmjs.org/async/-/async-0.1.15.tgz
npm http 200 http://registry.npmjs.org/socket.io-client/0.9.11
npm http GET http://registry.npmjs.org/socket.io-client/-/socket.io-client-0.9.11.tgz
npm http 200 http://registry.npmjs.org/redis/0.7.3
npm http GET http://registry.npmjs.org/redis/-/redis-0.7.3.tgz
npm http 200 http://registry.npmjs.org/prelude-ls
npm http GET http://registry.npmjs.org/prelude-ls/-/prelude-ls-0.6.0.tgz
npm http 200 http://registry.npmjs.org/semver
npm http GET http://registry.npmjs.org/semver/-/semver-1.1.4.tgz
npm http 200 http://registry.npmjs.org/esprima
npm http GET http://registry.npmjs.org/esprima/-/esprima-0.9.9.tgz
npm http 200 http://registry.npmjs.org/mkdirp
npm http GET http://registry.npmjs.org/mkdirp/-/mkdirp-0.3.5.tgz
npm http 200 http://registry.npmjs.org/handlebars
npm http GET http://registry.npmjs.org/handlebars/-/handlebars-1.0.10.tgz
npm http 200 http://registry.npmjs.org/fileset
npm http GET http://registry.npmjs.org/fileset/-/fileset-0.1.5.tgz
npm http 200 http://registry.npmjs.org/nopt
npm http GET http://registry.npmjs.org/nopt/-/nopt-2.0.0.tgz
npm http 200 http://registry.npmjs.org/which
npm http GET http://registry.npmjs.org/which/-/which-1.0.5.tgz
npm http 200 http://registry.npmjs.org/escodegen
npm http GET http://registry.npmjs.org/escodegen/-/escodegen-0.0.22.tgz
npm http 200 http://registry.npmjs.org/abbrev
npm http GET http://registry.npmjs.org/abbrev/-/abbrev-1.0.4.tgz
npm http 200 http://registry.npmjs.org/wordwrap
npm http 200 http://registry.npmjs.org/graceful-fs/-/graceful-fs-1.2.0.tgz
npm http 200 http://registry.npmjs.org/inherits/-/inherits-1.0.0.tgz
npm http 200 http://registry.npmjs.org/pkginfo
npm http GET http://registry.npmjs.org/pkginfo/-/pkginfo-0.2.3.tgz
npm http 200 http://registry.npmjs.org/base64id/-/base64id-0.1.0.tgz
npm http 200 http://registry.npmjs.org/wordwrap/-/wordwrap-0.0.2.tgz
npm http 200 http://registry.npmjs.org/lru-cache/-/lru-cache-2.3.0.tgz
npm http 200 http://registry.npmjs.org/policyfile/-/policyfile-0.0.4.tgz
npm http 200 http://registry.npmjs.org/readable-stream
npm http GET http://registry.npmjs.org/readable-stream/-/readable-stream-1.0.2.tgz
npm http 200 http://registry.npmjs.org/utile
npm http GET http://registry.npmjs.org/utile/-/utile-0.1.7.tgz
npm http 200 http://registry.npmjs.org/async/-/async-0.1.15.tgz
npm http 200 http://registry.npmjs.org/socket.io-client/-/socket.io-client-0.9.11.tgz
npm http 200 http://registry.npmjs.org/dequeue/-/dequeue-1.0.3.tgz
npm http 200 http://registry.npmjs.org/redis/-/redis-0.7.3.tgz
npm http 200 http://registry.npmjs.org/prelude-ls/-/prelude-ls-0.6.0.tgz
npm http 200 http://registry.npmjs.org/semver/-/semver-1.1.4.tgz
npm http 200 http://registry.npmjs.org/esprima/-/esprima-0.9.9.tgz
npm http 200 http://registry.npmjs.org/mkdirp/-/mkdirp-0.3.5.tgz
npm http 200 http://registry.npmjs.org/handlebars/-/handlebars-1.0.10.tgz
npm http 200 http://registry.npmjs.org/sigmund
npm http GET http://registry.npmjs.org/sigmund/-/sigmund-1.0.0.tgz
npm http 200 http://registry.npmjs.org/fileset/-/fileset-0.1.5.tgz
npm http 200 http://registry.npmjs.org/nopt/-/nopt-2.0.0.tgz
npm http 200 http://registry.npmjs.org/which/-/which-1.0.5.tgz
npm http 200 http://registry.npmjs.org/async
npm http 200 http://registry.npmjs.org/escodegen/-/escodegen-0.0.22.tgz
npm http GET http://registry.npmjs.org/async/-/async-0.1.22.tgz
npm http 200 http://registry.npmjs.org/abbrev/-/abbrev-1.0.4.tgz
npm http 200 http://registry.npmjs.org/pkginfo/-/pkginfo-0.2.3.tgz
npm http 200 http://registry.npmjs.org/readable-stream/-/readable-stream-1.0.2.tgz
npm http 200 http://registry.npmjs.org/utile/-/utile-0.1.7.tgz
npm http 200 http://registry.npmjs.org/sigmund/-/sigmund-1.0.0.tgz
npm http GET http://registry.npmjs.org/deep-equal
npm http 200 http://registry.npmjs.org/async/-/async-0.1.22.tgz
npm http GET http://registry.npmjs.org/i
npm http GET http://registry.npmjs.org/ncp
npm http GET http://registry.npmjs.org/rimraf
npm http 200 http://registry.npmjs.org/deep-equal
npm http GET http://registry.npmjs.org/deep-equal/-/deep-equal-0.0.0.tgz
npm http 304 http://registry.npmjs.org/rimraf
npm http GET http://registry.npmjs.org/rimraf/-/rimraf-1.0.9.tgz
npm http 200 http://registry.npmjs.org/i
npm http GET http://registry.npmjs.org/i/-/i-0.3.1.tgz
npm http 200 http://registry.npmjs.org/deep-equal/-/deep-equal-0.0.0.tgz
npm http 200 http://registry.npmjs.org/rimraf/-/rimraf-1.0.9.tgz
npm http 200 http://registry.npmjs.org/ncp
npm http GET http://registry.npmjs.org/ncp/-/ncp-0.2.7.tgz
npm http 200 http://registry.npmjs.org/i/-/i-0.3.1.tgz
npm http 404 http://registry.npmjs.org/ncp/-/ncp-0.2.7.tgz
npm ERR! fetch failed http://registry.npmjs.org/ncp/-/ncp-0.2.7.tgz
npm ERR! Error: 404 Not Found
npm ERR!     at WriteStream.<anonymous> (/home/smanastirliu/Scaricati/node-v0.10.5-linux-x86/lib/node_modules/npm/lib/utils/fetch.js:57:12)
npm ERR!     at WriteStream.EventEmitter.emit (events.js:117:20)
npm ERR!     at fs.js:1596:14
npm ERR!     at Object.oncomplete (fs.js:107:15)
npm ERR! If you need help, you may report this log at:
npm ERR!     <http://github.com/isaacs/npm/issues>
npm ERR! or email it to:
npm ERR!     <npm-@googlegroups.com>

npm ERR! System Linux 3.5.0-27-generic
npm ERR! command "/usr/local/bin/node" "/usr/local/bin/npm" "install" "karma"
npm ERR! cwd /home/smanastirliu
npm ERR! node -v v0.10.5
npm ERR! npm -v 1.2.18
npm http GET http://registry.npmjs.org/uglify-js/1.2.5
npm http GET http://registry.npmjs.org/ws
npm http GET http://registry.npmjs.org/xmlhttprequest/1.4.2
npm http GET http://registry.npmjs.org/active-x-obfuscator/0.0.1
npm http 404 http://registry.npmjs.org/uglify-js/1.2.5
npm ERR! registry error parsing json
npm http 404 http://registry.npmjs.org/xmlhttprequest/1.4.2
npm ERR! registry error parsing json
npm http 404 http://registry.npmjs.org/active-x-obfuscator/0.0.1
npm ERR! registry error parsing json
npm http 404 http://registry.npmjs.org/ws
npm ERR! registry error parsing json
npm http GET http://registry.npmjs.org/source-map
npm http GET http://registry.npmjs.org/estraverse
npm http GET http://registry.npmjs.org/esprima
npm http GET http://registry.npmjs.org/uglify-js
npm http 404 http://registry.npmjs.org/esprima
npm ERR! registry error parsing json
npm http 404 http://registry.npmjs.org/source-map
npm ERR! registry error parsing json
npm WARN optional dep failed, continuing source-map@>= 0.1.2
npm http GET http://registry.npmjs.org/esprima/-/esprima-1.0.2.tgz
npm http 404 http://registry.npmjs.org/estraverse
npm ERR! registry error parsing json
npm http 404 http://registry.npmjs.org/uglify-js
npm ERR! registry error parsing json
npm http 404 http://registry.npmjs.org/esprima/-/esprima-1.0.2.tgz
npm ERR! fetch failed http://registry.npmjs.org/esprima/-/esprima-1.0.2.tgz
npm ERR! 
npm ERR! Additional logging details can be found in:
npm ERR!     /home/smanastirliu/npm-debug.log
npm ERR! not ok code 0

Calling the packages url from browser I get a strange response (same response for any url):

<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <script type="text/javascript" language="JavaScript" src="http://img.sedoparking.com/registrar/dopark.js"></script>
  </head>
  <body style="display: none;">
    <script type="text/javascript">
var reg = 'sedonewreg';
document.write( '<scr'+'ipt type="text/javascript" language="JavaScript"' + 'src="http://sedoparking.com/' + window.location.host + '/' + reg + '/park.js">' + '</scr' + 'ipt>' );
    </script>
 </body>
</html>

It seems to be a proxy error: I’m investigating

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

В этом материале я расскажу о семи распространённых ошибках, которые веб-разработчики допускают при работе с npm. В частности, речь пойдёт об управлении зависимостями, о публикации пакетов и ещё о некоторых важных вещах.

1. Ручное добавление зависимостей в файл package.json

Не стоит самостоятельно редактировать файл package.json, так как это может нарушить синхронизацию между этим файлом и package-lock.json.

Вместо этого можно прибегнуть к командам, выполняемым в командной строке, вроде npm i --save и npm i --save-dev, что позволит автоматически обновлять и package.json, и package-lock.json. При таком подходе система ещё и уведомит разработчика о том, что в версиях зависимостей, упомянутых в этих двух файлах, имеются расхождения.

Правда, надо отметить, что использование подобных команд не всегда гарантирует беспроблемное обновление зависимостей.

Например, если выполнить команду вида npm i --save package@~1.0.0, можно ожидать, что в package.json будет отражена версия пакета, соответствующая той, что указана в команде после @. Но в подобной команде можно использовать не спецификатор версии ~, а спецификатор версии ^, что позволит расширить возможности по автоматическому обновлению пакета.

Рекомендуется тщательно проверять package.json после обновления зависимостей.

2. Ограничение зависимостей типа peerDependencies конкретной версией патча

Обычно зависимости типа peerDependencies используются для того чтобы обеспечить правильную работу плагинов с хост-пакетами. Если ограничить подобные зависимости конкретными версиями патчей — результат может оказаться не очень хорошим.

Рассмотрим простой пример для того чтобы разобраться с фундаментальной причиной этой проблемы.

{
  "name": "tea-latte",
  "peerDependencies": {
    "tea": "1.x"
  }
}

В соответствии с вышеприведённым кодом, модуль tea-latte нуждается в конкретной версии (1.x) пакета tea.

Но в проекте могут быть другие пакеты или модули, которые зависят от самой свежей версии пакета tea. В результате ограничение версии пакета tea может привести к непредсказуемому поведению приложения.

Обратите внимание на то, что npm версий 1, 2 и 7 автоматически установит зависимости peerDependencies, если явной зависимости от них нет, выше в дереве зависимостей. А npm версий 3, 4, 5 и 6 выдаст предупреждение.

3. Публикация нескольких модулей в виде единственного пакета

Независимый компонент и схема его зависимостей

Идёт ли речь об UI-библиотеке, о наборе полезных инструментов, или о любой другой группе модулей,  публикация нескольких таких сущностей в виде единого пакета — это, практически всегда, неудачная идея.

Нет причин, по которым разработчикам стоит принуждать потребителей их кода привязывать свои проекты к целому набору модулей и компонентов, в ситуациях, когда потребителям все эти модули или компоненты не нужны. У потребителей должна быть возможность выбора конкретного модуля и его версии, он не должен сталкиваться с бессмысленными обновлениями пакетов, происходящими из-за того, что ему не нужно.

Вы, вероятнее всего, согласитесь с вышесказанным, но вас может напугать мысль о необходимости управления монорепозиторием для поддержки всех этих пакетов. На это я могу сказать, что бояться тут нечего.

JavaScript-экосистема уже далеко ушла от тех времён, когда шёл спор между приверженцами монорепозиториев и полирепозиториев.

Теперь мы можем пользоваться возможностями публикации независимых компонентов из простых проектов, наподобие тех, что созданы с использованием Create React App, с возможностью контроля версий, с автоматическим созданием package.json, документации и многого другого. В частности, такие возможности даёт платформа Bit.

4. Случайная публикация секретных данных

Если вы случайно опубликовали модуль, содержащий секретные данные, то первым делом нужно отменить его публикацию.

Но это не решает проблему утечки данных, так как после того, как модуль опубликован, он копируется на все зеркала репозитория пакетов. И если отменить его публикацию — это не позволит исправить ситуацию.

Использование белых списков — это удобный способ, используемый для контроля того, что публикуется в репозиториях пакетов, и для предотвращения публикации секретных данных.

Для применения белых списков публикуемых материалов достаточно добавить в package.json свойство с именем files. В нём можно указать список файлов или папок, которые подлежат публикации.

{
 “name”: “my-package”,
 “version”: “1.0.0”,
 “description”: “my-package”,
 “scripts”: {
 “test”: “echo ”Error: no test specified” && exit 1"
 },
 “files”: [
 “dist/”
 ],
 “keywords”: [],
 “author”: “bhagya-withana”
}

Рекомендую использовать белые списки для управления тем, что попадает в пакеты, которые планируется публиковать.

5. Использование обычного токена аутентификации

Если вы используете в CI/CD-цепочке приватные модули, вам понадобится воспользоваться токеном аутентификации. Но инструменты npm, работающие в командной строке, при создании подобных токенов не позволяют управлять правами на чтение и на запись.

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

Нижеприведённая команда позволяет создать токен с ограничением доступа только чтением данных:

curl -u [USERNAME]:[PASSWORD] https://registry.npmjs.org/-/npm/v1/tokens 
-X POST -H 'content-type: application/json' 
-d '{"password":"[USERNAME]", "readonly": "true"}'

На сайте npm можно просматривать, добавлять и удалять подобные токены.

Команда для доступа к операциям с токенами

6. Бессмысленное обновление пакетов

Использование самых свежих версий пакетов — это хорошо. Но не стоит обновлять пакеты только из-за того, что выходят их новые версии. Разберёмся с причинами этой рекомендации:

  • В самой свежей версии пакета могут быть ошибки.
  • Обновление пакетов без тщательного изучения изменений может привести к неожиданным эффектам в приложении.
  • Новые возможности могут оказаться ненужными в конкретном проекте.
  • Установка самой свежей версии некоего пакета может привести к проблемам в работе других пакетов, которые от него зависят.

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

7. Удаление файла package-lock.json

Веб-разработчики часто удаляют файл package-lock.json для того чтобы решить проблемы, возникающие при работе с npm.

Но так лучше не делать, так как этот файл хранит сведения о точной версии каждого установленного пакета. Если, например, выполнить команду npm update, сведения об обновлённых зависимостях будут отражены в файле package-lock.json.

В результате, вместо того, чтобы, в попытке решения некоей проблемы, удалять файл package-lock.json, можно попробовать следующее:

  • Разрешить конфликты package.json.
  • Изъять package-lock.json из главной ветки репозитория.
  • Снова выполнить команду npm install.

Итоги

Npm — это важнейшая часть любого проекта, основанного на JavaScript, этот менеджер пакетов помогает разработчикам эффективно управлять зависимостями своих проектов.

Но работа с npm сопряжена с множеством ошибок, некоторые из которых могут привести к серьёзным проблемам. Хочется надеяться, что то, о чём мы говорили в этом материале, поможет вам совершать меньше ошибок при работе с npm.

Сталкивались ли вы когда-нибудь с проблемами, вызванными ошибками, допущенными при работе с npm?

Содержание

  1. Common errors
  2. AppDataRoamingnpm’ on Windows 7 permalink» >
  3. Распространённые ошибки при использовании npm, которых лучше не совершать
  4. 1. Ручное добавление зависимостей в файл package.json
  5. 2. Ограничение зависимостей типа peerDependencies конкретной версией патча
  6. 3. Публикация нескольких модулей в виде единственного пакета
  7. 4. Случайная публикация секретных данных
  8. 5. Использование обычного токена аутентификации
  9. 6. Бессмысленное обновление пакетов
  10. 7. Удаление файла package-lock.json
  11. Итоги
  12. Common errors
  13. Errors
  14. Сломанная установка npm
  15. Random errors
  16. Не найдена совместимая версия
  17. Permissions errors
  18. Error: ENOENT, stat ‘C:Users AppDataRoamingnpm’ on Windows 7″ onmousemove=»i18n(this)»> Error: ENOENT, stat ‘C:Users AppDataRoamingnpm’ в Windows 7
  19. No space
  20. No git
  21. Запуск блока Vagrant на Windows не удается из-за проблем с длиной пути
  22. git: and ssh+git: URLs for GitHub repos, breaking proxies» onmousemove=»i18n(this)»>npm использует только git: и ssh+git: URL-адреса для репозиториев GitHub, нарушая прокси
  23. SSL Error
  24. SSL-intercepting proxy
  25. Не найдено/Ошибка сервера
  26. Invalid JSON
  27. ENOENT / ENOTEMPTY errors in output» onmousemove=»i18n(this)»>Многие ошибки ENOENT / ENOTEMPTY в выводе
  28. cb() never called! when using shrinkwrapped dependencies» onmousemove=»i18n(this)»> cb() never called! при использовании термоусадочных зависимостей
  29. npm login errors» onmousemove=»i18n(this)»> npm login ошибки входа в npm
  30. npm hangs on Windows at addRemoteTarball » onmousemove=»i18n(this)»> npm зависает в Windows на addRemoteTarball

Common errors

Broken npm installation

If your npm is broken:

  • On Mac or Linux, reinstall npm.
  • Windows: If you’re on Windows and you have a broken installation, the easiest thing to do is to reinstall node from the official installer (see this note about installing the latest stable version).
  • Some strange issues can be resolved by simply running npm cache clean and trying again.
  • If you are having trouble with npm install , use the -verbose option to see more details.

No compatible version found

AppDataRoamingnpm’ on Windows 7 permalink» >

Error: ENOENT, stat ‘C:Users AppDataRoamingnpm’ on Windows 7

The error Error: ENOENT, stat ‘C:Users AppDataRoamingnpm’ on Windows 7 is a consequence of joyent/node#8141, and is an issue with the Node installer for Windows. The workaround is to ensure that C:Users AppDataRoamingnpm exists and is writable with your normal user account.

You are trying to install on a drive that either has no space, or has no permission to write.

  • Free some disk space or
  • Set the tmp folder somewhere with more space: npm config set tmp /path/to/big/drive/tmp or
  • Build Node yourself and install it somewhere writable with lots of space.

You need to install git. Or, you may need to add your git information to your npm profile. You can do this from the command line or the website. For more information, see «Managing your profile settings».

Running a Vagrant box on Windows fails due to path length issues

@drmyersii went through what sounds like a lot of painful trial and error to come up with a working solution involving Windows long paths and some custom Vagrant configuration:

In the code above, I am appending \? to the current directory absolute path. This will actually force the Windows API to allow an increase in the MAX_PATH variable (normally capped at 260). Read more about max path. This is happening during the sharedfolder creation which is intentionally handled by VBoxManage and not Vagrant’s «synced_folder» method. The last bit is pretty self-explanatory; we create the new shared folder and then make sure it’s mounted each time the machine is accessed or touched since Vagrant likes to reload its mounts/shared folders on each load.

npm only uses git: and ssh+git: URLs for GitHub repos, breaking proxies

I fixed this issue for several of my colleagues by running the following two commands:

One thing we noticed is that the .gitconfig used is not always the one expected so if you are on a machine that modified the home path to a shared drive, you need to ensure that your .gitconfig is the same on both your shared drive and in c:users[your user]

You are trying to talk SSL to an unencrypted endpoint. More often than not, this is due to a proxy configuration error (see also this helpful, if dated, guide). In this case, you do not want to disable strict-ssl – you may need to set up a CA / CA file for use with your proxy, but it’s much better to take the time to figure that out than disabling SSL protection.

This problem will happen if you’re running Node 0.6. Please upgrade to node 0.8 or above. See this post for details.

You could also try these workarounds: npm config set ca «» or npm config set strict-ssl false

  • upgrade your version of npm npm install npm -g —ca=»»
  • tell your current version of npm to use known registrars npm config set ca=»»

If this does not fix the problem, then you may have an SSL-intercepting proxy. (For example, https://github.com/npm/npm/issues/7439#issuecomment-76024878)

Not found / Server error

  • It’s most likely a temporary npm registry glitch. Check npm server status and try again later.
  • If the error persists, perhaps the published package is corrupt. Contact the package owner and have them publish a new version of the package.
  • Possible temporary npm registry glitch, or corrupted local server cache. Run npm cache clean and/or try again later.
  • This can be caused by corporate proxies that give HTML responses to package.json requests. Check npm’s proxy configuration.
  • Check that it’s not a problem with a package you’re trying to install (e.g. invalid package.json ).

Many ENOENT / ENOTEMPTY errors in output

npm is written to use resources efficiently on install, and part of this is that it tries to do as many things concurrently as is practical. Sometimes this results in race conditions and other synchronization issues. As of npm 2.0.0, a very large number of these issues were addressed. If you see ENOENT lstat , ENOENT chmod , ENOTEMPTY unlink , or something similar in your log output, try updating npm to the latest version. If the problem persists, look at npm/npm#6043 and see if somebody has already discussed your issue.

cb() never called! when using shrinkwrapped dependencies

Take a look at issue #5920. We’re working on fixing this one, but it’s a fairly subtle race condition and it’s taking us a little time. You might try moving your npm-shrinkwrap.json file out of the way until we have this fixed. This has been fixed in versions of npm newer than npm@2.1.5 , so update to npm@latest .

npm login errors

Sometimes npm login fails for no obvious reason. The first thing to do is to log in at https://www.npmjs.com/login and check that your e-mail address on npmjs.com matches the email address you are giving to npm login .

If that’s not the problem, or if you are seeing the message «may not mix password_sha and pbkdf2» , then

  1. Log in at https://npmjs.com/
  2. Change password at https://npmjs.com/password – you can even «change» it to the same password
  3. Clear login-related fields from

/.npmrc – e.g., by running sed -ie ‘/registry.npmjs.org/d’

and it generally seems to work.

npm hangs on Windows at addRemoteTarball

Check if you have two temp directories set in your .npmrc :

Look for lines defining the tmp config variable. If you find more than one, remove all but one of them.

See https://github.com/npm/npm/issues/7590 for more about this unusual problem.

npm not running the latest version on a Windows machine

Источник

Распространённые ошибки при использовании npm, которых лучше не совершать

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

В этом материале я расскажу о семи распространённых ошибках, которые веб-разработчики допускают при работе с npm. В частности, речь пойдёт об управлении зависимостями, о публикации пакетов и ещё о некоторых важных вещах.

1. Ручное добавление зависимостей в файл package.json

Не стоит самостоятельно редактировать файл package.json , так как это может нарушить синхронизацию между этим файлом и package-lock.json .

Вместо этого можно прибегнуть к командам, выполняемым в командной строке, вроде npm i —save и npm i —save-dev , что позволит автоматически обновлять и package.json , и package-lock.json . При таком подходе система ещё и уведомит разработчика о том, что в версиях зависимостей, упомянутых в этих двух файлах, имеются расхождения.

Правда, надо отметить, что использование подобных команд не всегда гарантирует беспроблемное обновление зависимостей.

Например, если выполнить команду вида npm i —save package@

1.0.0 , можно ожидать, что в package.json будет отражена версия пакета, соответствующая той, что указана в команде после @ . Но в подобной команде можно использовать не спецификатор версии

, а спецификатор версии ^ , что позволит расширить возможности по автоматическому обновлению пакета.

Рекомендуется тщательно проверять package.json после обновления зависимостей.

2. Ограничение зависимостей типа peerDependencies конкретной версией патча

Обычно зависимости типа peerDependencies используются для того чтобы обеспечить правильную работу плагинов с хост-пакетами. Если ограничить подобные зависимости конкретными версиями патчей — результат может оказаться не очень хорошим.

Рассмотрим простой пример для того чтобы разобраться с фундаментальной причиной этой проблемы.

В соответствии с вышеприведённым кодом, модуль tea-latte нуждается в конкретной версии (1.x) пакета tea .

Но в проекте могут быть другие пакеты или модули, которые зависят от самой свежей версии пакета tea . В результате ограничение версии пакета tea может привести к непредсказуемому поведению приложения.

Обратите внимание на то, что npm версий 1, 2 и 7 автоматически установит зависимости peerDependencies , если явной зависимости от них нет, выше в дереве зависимостей. А npm версий 3, 4, 5 и 6 выдаст предупреждение.

3. Публикация нескольких модулей в виде единственного пакета

Независимый компонент и схема его зависимостей

Идёт ли речь об UI-библиотеке, о наборе полезных инструментов, или о любой другой группе модулей, публикация нескольких таких сущностей в виде единого пакета — это, практически всегда, неудачная идея.

Нет причин, по которым разработчикам стоит принуждать потребителей их кода привязывать свои проекты к целому набору модулей и компонентов, в ситуациях, когда потребителям все эти модули или компоненты не нужны. У потребителей должна быть возможность выбора конкретного модуля и его версии, он не должен сталкиваться с бессмысленными обновлениями пакетов, происходящими из-за того, что ему не нужно.

Вы, вероятнее всего, согласитесь с вышесказанным, но вас может напугать мысль о необходимости управления монорепозиторием для поддержки всех этих пакетов. На это я могу сказать, что бояться тут нечего.

JavaScript-экосистема уже далеко ушла от тех времён, когда шёл спор между приверженцами монорепозиториев и полирепозиториев.

Теперь мы можем пользоваться возможностями публикации независимых компонентов из простых проектов, наподобие тех, что созданы с использованием Create React App, с возможностью контроля версий, с автоматическим созданием package.json , документации и многого другого. В частности, такие возможности даёт платформа Bit.

4. Случайная публикация секретных данных

Если вы случайно опубликовали модуль, содержащий секретные данные, то первым делом нужно отменить его публикацию.

Но это не решает проблему утечки данных, так как после того, как модуль опубликован, он копируется на все зеркала репозитория пакетов. И если отменить его публикацию — это не позволит исправить ситуацию.

Использование белых списков — это удобный способ, используемый для контроля того, что публикуется в репозиториях пакетов, и для предотвращения публикации секретных данных.

Для применения белых списков публикуемых материалов достаточно добавить в package.json свойство с именем files . В нём можно указать список файлов или папок, которые подлежат публикации.

Рекомендую использовать белые списки для управления тем, что попадает в пакеты, которые планируется публиковать.

5. Использование обычного токена аутентификации

Если вы используете в CI/CD-цепочке приватные модули, вам понадобится воспользоваться токеном аутентификации. Но инструменты npm, работающие в командной строке, при создании подобных токенов не позволяют управлять правами на чтение и на запись.

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

Нижеприведённая команда позволяет создать токен с ограничением доступа только чтением данных:

На сайте npm можно просматривать, добавлять и удалять подобные токены.

Команда для доступа к операциям с токенами

6. Бессмысленное обновление пакетов

Использование самых свежих версий пакетов — это хорошо. Но не стоит обновлять пакеты только из-за того, что выходят их новые версии. Разберёмся с причинами этой рекомендации:

  • В самой свежей версии пакета могут быть ошибки.
  • Обновление пакетов без тщательного изучения изменений может привести к неожиданным эффектам в приложении.
  • Новые возможности могут оказаться ненужными в конкретном проекте.
  • Установка самой свежей версии некоего пакета может привести к проблемам в работе других пакетов, которые от него зависят.

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

7. Удаление файла package-lock.json

Веб-разработчики часто удаляют файл package-lock.json для того чтобы решить проблемы, возникающие при работе с npm.

Но так лучше не делать, так как этот файл хранит сведения о точной версии каждого установленного пакета. Если, например, выполнить команду npm update , сведения об обновлённых зависимостях будут отражены в файле package-lock.json .

В результате, вместо того, чтобы, в попытке решения некоей проблемы, удалять файл package-lock.json , можно попробовать следующее:

  • Разрешить конфликты package.json .
  • Изъять package-lock.json из главной ветки репозитория.
  • Снова выполнить команду npm install .

Итоги

Npm — это важнейшая часть любого проекта, основанного на JavaScript, этот менеджер пакетов помогает разработчикам эффективно управлять зависимостями своих проектов.

Но работа с npm сопряжена с множеством ошибок, некоторые из которых могут привести к серьёзным проблемам. Хочется надеяться, что то, о чём мы говорили в этом материале, поможет вам совершать меньше ошибок при работе с npm.

Сталкивались ли вы когда-нибудь с проблемами, вызванными ошибками, допущенными при работе с npm?

Источник

Common errors

Errors

Сломанная установка npm

Если ваш npm сломан:

  • На Mac или Linux переустановите npm .
  • Windows: если вы используете Windows и у вас не работает установка, проще всего переустановить узел из официального установщика (см. Это примечание об установке последней стабильной версии ).

Random errors

  • npm cache clean and trying again.» onmousemove=»i18n(this)»>Некоторые странные проблемы можно решить, просто запустив npm cache clean и повторив попытку.
  • npm install , use the -verbose option to see more details.» onmousemove=»i18n(this)»>Если у вас возникли проблемы с npm install , используйте параметр -verbose , чтобы увидеть более подробную информацию.

Не найдена совместимая версия

Permissions errors

См. Обсуждения в разделах « Загрузка и установка Node.js и npm » и « Устранение ошибок разрешений EACCES при глобальной установке пакетов », чтобы узнать, как избежать и устранить ошибки разрешений.

Error: ENOENT, stat ‘C:Users AppDataRoamingnpm’ on Windows 7″ onmousemove=»i18n(this)»> Error: ENOENT, stat ‘C:Users AppDataRoamingnpm’ в Windows 7

Error: ENOENT, stat ‘C:Users AppDataRoamingnpm’ on Windows 7 is a consequence of joyent/node#8141, and is an issue with the Node installer for Windows. The workaround is to ensure that C:Users AppDataRoamingnpm exists and is writable with your normal user account.» onmousemove=»i18n(this)»>Ошибка Error: ENOENT, stat ‘C:Users AppDataRoamingnpm’ в Windows 7 является следствием joyent / node # 8141 и является проблемой установщика Node для Windows. Обходной путь — убедиться, что C:Users AppDataRoamingnpm существует и доступен для записи с вашей обычной учетной записью.

No space

Вы пытаетесь установить диск,на котором либо нет места,либо нет разрешения на запись.

  • Освободите место на диске или
  • npm config set tmp /path/to/big/drive/tmp or» onmousemove=»i18n(this)»>Установите папку tmp где-нибудь с большим пространством: npm config set tmp /path/to/big/drive/tmp или
  • Соберите Node самостоятельно и установите его где-нибудь,где есть место для записи с большим количеством места.

No git

Вам необходимо установить git . Или вам может потребоваться добавить информацию о git в свой профиль npm. Вы можете сделать это из командной строки или на веб-сайте. Для получения дополнительной информации см. « Управление настройками вашего профиля ».

Запуск блока Vagrant на Windows не удается из-за проблем с длиной пути

@drmyersii прошел через много мучительных проб и ошибок, чтобы предложить рабочее решение, включающее длинные пути Windows и некоторую настраиваемую конфигурацию Vagrant:

\? to the current directory absolute path. This will actually force the Windows API to allow an increase in the MAX_PATH variable (normally capped at 260). Read more about max path. This is happening during the sharedfolder creation which is intentionally handled by VBoxManage and not Vagrant’s «synced_folder» method. The last bit is pretty self-explanatory; we create the new shared folder and then make sure it’s mounted each time the machine is accessed or touched since Vagrant likes to reload its mounts/shared folders on each load.» onmousemove=»i18n(this)»>В приведенном выше коде я добавляю \? К абсолютному пути текущего каталога. Это фактически заставит Windows API разрешить увеличение переменной MAX_PATH (обычно не более 260). Подробнее о максимальном пути . Это происходит во время создания общей папки, которая намеренно обрабатывается VBoxManage, а не методом Vagrant «synced_folder». Последний пункт довольно понятен; мы создаем новую общую папку, а затем убеждаемся, что она монтируется каждый раз, когда к машине обращаются или касаются, поскольку Vagrant любит перезагружать свои монтированные / общие папки при каждой загрузке.

git: and ssh+git: URLs for GitHub repos, breaking proxies» onmousemove=»i18n(this)»>npm использует только git: и ssh+git: URL-адреса для репозиториев GitHub, нарушая прокси

@LaurentGoderre исправил это с помощью некоторых уловок Git :

Я исправил эту проблему для нескольких своих коллег,запустив следующие две команды:

.gitconfig used is not always the one expected so if you are on a machine that modified the home path to a shared drive, you need to ensure that your .gitconfig is the same on both your shared drive and in c:users[your user] » onmousemove=»i18n(this)»>Одна вещь, которую мы заметили, заключается в том, что используемый .gitconfig не всегда является ожидаемым, поэтому, если вы находитесь на машине, которая изменила домашний путь к общему диску, вам необходимо убедиться, что ваш .gitconfig одинаков как на вашем общем диске, так и на в c:users[your user]

SSL Error

strict-ssl – you may need to set up a CA / CA file for use with your proxy, but it’s much better to take the time to figure that out than disabling SSL protection.» onmousemove=»i18n(this)»>Вы пытаетесь подключить SSL к незашифрованной конечной точке. Чаще всего это связано с ошибкой конфигурации прокси (см. также это полезное, хотя и устаревшее, руководство ). В этом случае вам не нужно отключать strict-ssl — вам может понадобиться настроить файл CA/CA для использования с вашим прокси, но гораздо лучше потратить время на то, чтобы разобраться в этом, чем отключать защиту SSL.

Эта проблема может возникнуть, если вы используете Node 0.6. Пожалуйста, обновите до версии 0.8 или выше. Подробности смотрите в этом посте .

npm config set ca «» or npm config set strict-ssl false ‘ onmousemove=»i18n(this)»>Вы также можете попробовать следующие обходные пути: npm config set ca «» или npm config set strict-ssl false

  • npm install npm -g —ca=»» ‘ onmousemove=»i18n(this)»>обновите свою версию npm npm install npm -g —ca=»»
  • npm config set ca=»» ‘ onmousemove=»i18n(this)»>указать вашей текущей версии npm использовать известных регистраторов npm config set ca=»»

Если это не решит проблему, возможно, у вас прокси для перехвата SSL. (Например, https://github.com/npm/npm/issues/7439#issuecomment-76024878 )

SSL-intercepting proxy

Не найдено/Ошибка сервера

  • Скорее всего, это временный сбой реестра npm. Проверьте статус сервера npm и повторите попытку позже.
  • Если ошибка сохраняется,возможно,опубликованный пакет поврежден.Свяжитесь с владельцем пакета и попросите его опубликовать новую версию пакета.

Invalid JSON

  • npm cache clean and/or try again later.» onmousemove=»i18n(this)»>Возможный временный сбой реестра npm или поврежденный кеш локального сервера. Запустите npm cache clean и / или повторите попытку позже.
  • package.json requests. Check npm’s proxy configuration.» onmousemove=»i18n(this)»>Это может быть вызвано корпоративными прокси, которые дают HTML-ответы на запросы package.json . Проверьте конфигурацию прокси-сервера npm .
  • package.json ).» onmousemove=»i18n(this)»>Убедитесь, что это не проблема с пакетом, который вы пытаетесь установить (например, недопустимый package.json ).

ENOENT / ENOTEMPTY errors in output» onmousemove=»i18n(this)»>Многие ошибки ENOENT / ENOTEMPTY в выводе

ENOENT lstat , ENOENT chmod , ENOTEMPTY unlink , or something similar in your log output, try updating npm to the latest version. If the problem persists, look at npm/npm#6043 and see if somebody has already discussed your issue.’ onmousemove=»i18n(this)»>npm написан для эффективного использования ресурсов при установке, и отчасти это связано с тем, что он пытается делать столько вещей одновременно, сколько это возможно. Иногда это приводит к состояниям гонки и другим проблемам синхронизации. Начиная с npm 2.0.0, было решено очень большое количество этих проблем. Если в выводе журнала вы видите ENOENT lstat , ENOENT chmod , ENOTEMPTY unlink или что-то подобное, попробуйте обновить npm до последней версии. Если проблема не исчезнет, ​​посмотрите npm / npm # 6043 и посмотрите, обсуждал ли кто-нибудь вашу проблему.

cb() never called! when using shrinkwrapped dependencies» onmousemove=»i18n(this)»> cb() never called! при использовании термоусадочных зависимостей

We’re working on fixing this one, but it’s a fairly subtle race condition and it’s taking us a little time. You might try moving your npm-shrinkwrap.json file out of the way until we have this fixed. This has been fixed in versions of npm newer than npm@2.1.5 , so update to npm@latest .» onmousemove=»i18n(this)»>Взгляните на выпуск # 5920 . Мы работаем над исправлением этого, но это довольно сложное состояние гонки, и это отнимает у нас немного времени. Вы можете попробовать переместить файл npm-shrinkwrap.json в сторону, пока мы не исправим это. Это было исправлено в версиях npm новее, чем npm@2.1.5 , поэтому обновите до npm@latest .

npm login errors» onmousemove=»i18n(this)»> npm login ошибки входа в npm

npm login fails for no obvious reason. The first thing to do is to log in at https://www.npmjs.com/login and check that your e-mail address on npmjs.com matches the email address you are giving to npm login .’ onmousemove=»i18n(this)»>Иногда npm login завершается неудачно без очевидной причины. Первое, что нужно сделать, это войти в систему на https://www.npmjs.com/login и убедиться, что ваш адрес электронной почты на npmjs.com совпадает с адресом электронной почты, который вы указываете для npm login в npm .

«may not mix password_sha and pbkdf2″ , then» onmousemove=»i18n(this)»>Если проблема не в этом или вы видите сообщение «may not mix password_sha and pbkdf2» , то

  1. Авторизуйтесь на https://npmjs.com/
  2. Смените пароль на https://npmjs.com/password — вы даже можете «сменить» его на тот же пароль

/.npmrc – e.g., by running sed -ie ‘/registry.npmjs.org/d’

/.npmrc » onmousemove=»i18n(this)»>Очистите поля, связанные с входом в систему, из

/.npmrc , например, запустив sed -ie ‘/registry.npmjs.org/d’

и в целом,похоже,это работает.

npm hangs on Windows at addRemoteTarball » onmousemove=»i18n(this)»> npm зависает в Windows на addRemoteTarball

.npmrc :» onmousemove=»i18n(this)»>Проверьте, установлены ли в вашем .npmrc два временных каталога :

tmp config variable. If you find more than one, remove all but one of them.» onmousemove=»i18n(this)»>Найдите строки, определяющие переменную конфигурации tmp . Если вы найдете более одного, удалите все, кроме одного.

Источник

I am trying to globally install an npm module I just published. Every time I try to install, either from npm or the folder, I get this error.

npm ERR! Error: ENOENT, chmod '/usr/local/lib/node_modules/takeapeek/lib/cmd.js'
npm ERR! If you need help, you may report this log at:
npm ERR!     <http://github.com/isaacs/npm/issues>
npm ERR! or email it to:
npm ERR!     <npm-@googlegroups.com>

npm ERR! System Linux 3.8.0-19-generic
npm ERR! command "node" "/usr/local/bin/npm" "install" "-g" "takeapeek"
npm ERR! cwd /home/giodamlio
npm ERR! node -v v0.10.6
npm ERR! npm -v 1.3.6
npm ERR! path /usr/local/lib/node_modules/takeapeek/lib/cmd.js
npm ERR! code ENOENT
npm ERR! errno 34
npm ERR! 
npm ERR! Additional logging details can be found in:
npm ERR!     /home/giodamlio/npm-debug.log
npm ERR! not ok code 0

I am using sudo and I have triple checked everything in the package everything should work. I did some searching around, and saw a couple of similer cases none of which have been resolved. Here is what I tried.

  • Upgrade npm (sudo npm install -g npm)
  • Clear the global npm cache (sudo npm cache clear)
  • Clear the user npm cache (npm cache clear)

I noticed that the error had to do with the file I am linking to the path, specifically when npm tried to do a chmod. That shouldn’t be a problem, my lib/cli.js has normal permissions, and npm has superuser permissions during this install.

After digging through the npm docs I found an option that would stop npm from making the bin links(--no-bin-links), when I tried the install with it, it worked fine.

So what’s the deal? Is this some weird fringe case bug that has no solution yet?

Edit: For reference, here is the module I uploaded

mikemaccana's user avatar

mikemaccana

103k93 gold badges371 silver badges469 bronze badges

asked Aug 1, 2013 at 9:49

giodamelio's user avatar

9

Ok it looks like NPM is using your .gitignore as a base for the .npmignore file, and thus ignores /lib. If you add a blank .npmignore file into the root of your application, everything should work.

A better, more explicit approach is to use an allow-list rather than a disallow-list, and use the «files» field in package.json to specify the files in your package.

[edit] — more info on this behaviour here: https://docs.npmjs.com/cli/v7/using-npm/developers#keeping-files-out-of-your-package

answered Aug 2, 2013 at 15:03

badsyntax's user avatar

badsyntaxbadsyntax

9,2553 gold badges45 silver badges65 bronze badges

10

I ran into a similar problem,

npm cache clean

solved it.

Uri Agassi's user avatar

Uri Agassi

36.5k13 gold badges76 silver badges93 bronze badges

answered May 3, 2014 at 15:06

Genjuro's user avatar

GenjuroGenjuro

7,2657 gold badges39 silver badges61 bronze badges

2

This problem somehow arose for me on Mac when I was trying to run npm install -g bower. It was giving me a number of errors for not being able to find things like graceful-fs. I’m not sure how I installed npm originally, but it looks like perhaps it came down with node using homebrew. I first ran

brew uninstall node

This removed both node and npm from my path. From there I just reinstalled it

brew install node

When it completed I had node and npm on my path and I was able to run

rm -rf ~/.npm
npm install -g bower

This then installed bower successfully.

Updating the brew formulas and upgrading the installs didn’t seem to work for me, I’m not sure why. The removal of the .npm folder was something that had worked for other people, and I had tried it without success. I did it this time just in case. Note also that neither of the following solved the problem for me, although it did for others:

npm cache clean
sudo npm cache clean

answered Jan 9, 2014 at 23:52

user1978019's user avatar

user1978019user1978019

2,8081 gold badge28 silver badges37 bronze badges

0

I encountered similar behavior after upgrading to npm 6.1.0. It seemed to work once, but then I got into a state with this error while trying to install a package that was specified by path on the filesystem:

npm ERR! code ENOENT
npm ERR! errno -2
npm ERR! syscall rename

The following things did not fix the problem:

  • rm -rf node_modules
  • npm cache clean (gave npm ERR! As of npm@5, the npm cache self-heals….use 'npm cache verify' instead.)
  • npm cache verify
  • rm -rf ~/.npm

How I fixed the problem:

  • rm package-lock.json

answered Jul 12, 2018 at 12:50

Ian's user avatar

IanIan

10.8k2 gold badges35 silver badges57 bronze badges

I was getting this error on npm install and adding .npmignore did not solve it.

Error: ENOENT, stat ‘C:UsersMy-UserNameAppDataRoamingnpm’

I tried going to the mentioned folder and it did not exist.
The error was fixed when I created npm folder in Roaming folder.

This is on Windows 8.1

answered Nov 15, 2014 at 23:08

Vijay Vepakomma's user avatar

I had the same problem, and just found a handling not mentioned here. Though I’d contribute to the community:

npm install -g myapp was not copying the bin directory. I found this to be because I did not include it in the files in my package.json

"files": [
  "lib",
  "bin" // this was missing
]

answered Jun 11, 2015 at 0:26

dthree's user avatar

dthreedthree

19.2k14 gold badges75 silver badges105 bronze badges

3

Delete package-lock.json file then run npm install

answered Apr 13, 2021 at 6:00

Clark's user avatar

ClarkClark

1391 silver badge11 bronze badges

I was getting a similar error on npm install on a local installation:

npm ERR! enoent ENOENT: no such file or directory, stat '[path/to/local/installation]/node_modules/grunt-contrib-jst'

I am not sure what was causing the error, but I had recently installed a couple of new node modules locally, upgraded node with homebrew, and ran ‘npm update -g’.

The only way I was able to resolve the issue was to delete the local node_modules directory entirely and run npm install again:

cd [path/to/local/installation]
npm rm -rdf node_modules
npm install

answered Dec 31, 2015 at 0:40

g.carey's user avatar

g.careyg.carey

6807 silver badges6 bronze badges

I have a similar problem specifucally :
ERR! enoent ENOENT: no such file or directory, chmod ‘node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/bin/sshpk-conv
I tried all above solutions but no luck.
I was using vagrant box, and the project was in a shared folder. The problems seems to be only there, when I move the project to another not shared folder (woth host), voila! problem solved.
Just in case another person was using also vagrant

answered Mar 2, 2017 at 21:05

joaco1977's user avatar

1

I got the simple solution, just clear the npm cache.

sudo npm cache clear --force

then remove the node_modules & package-lock.json

sudo rm -rf node_modules
sudo rm -rf package-lock.json

Now install the dependencies module using npm and start the server

npm install && npm start

answered Jul 17, 2021 at 2:38

Abhishek Patel's user avatar

I got a similar error message when trying to npm install a bunch of dependencies. Turns out some of them fail to install on Debian/Ubuntu because they expect /usr/bin/node to be the node executable. To fix, you need do

sudo ln -s nodejs /usr/bin/node 

or better yet,

sudo apt-get install nodejs-legacy

For more info: https://stackoverflow.com/a/21171188/7581

Community's user avatar

answered Feb 19, 2015 at 6:26

itsadok's user avatar

itsadokitsadok

28.5k29 gold badges124 silver badges170 bronze badges

I got this error while trying to install a grunt plugin. i found i had an outdated version of npm and the error went away after updating npm to the latest version

npm install -g npm

answered Apr 4, 2015 at 16:13

Prabhu Murthy's user avatar

Prabhu MurthyPrabhu Murthy

8,9615 gold badges28 silver badges36 bronze badges

I think your compiled coffee script is missing from the published npm package. Try writing a prepublish command.

answered Aug 1, 2013 at 23:34

leeway's user avatar

leewayleeway

4751 gold badge3 silver badges8 bronze badges

2

In my case (multiple code ENOENT errno 34) problem was with ~/.npm/ directory access. Inside it there were some subdirs having root:root rights, which were causing problems while I run commands as normal user (without sudo). So I changed ownership of all subdirs and files inside ~/.npm/ dir into my local user and group. That did the trick on my Ubuntu (on Mac should work too).

$ sudo chown yourusername.yourgroupname ~/.npm/ -R

You should know your user name, right? If no then run $ whoami and substitute your group name with it too, like this:

$ sudo chown johnb.johnb ~/.npm/ -R

EDIT:

Test case:

From my local account /home/johnb I npm-installed globally some generator for yeoman, like this:

$ sudo npm install -g generator-laravel

Problem nature:

Above action caused some dependencies being installed inside ~/.npm/ dir, having root:root ownership (because of sudo ...). Evidently npm does not run as local user (or change dependencies subdirs ownership afterwards) when pulling dependencies and writing them to a local user subdir ~/.npm/.
As long as npm would be so careless against fundamental unix filesystem security issues the problem would reoccur.

Solution:

  1. Continuosly check if ~/.npm/ contains subdirs with ownership (and/or permissions) other than your local user account, especially when you install or update something with sodo (root). If so, change the ownership inside ~/.npm/ to a local user recursively.

  2. Ask npm, bower, grunt, ... community that they address this issue as I described it above.

answered May 28, 2014 at 22:10

paperclip's user avatar

Had a similar Issue but I was in wrong directory please cross check the path of thee file & the run npm start

answered May 2, 2022 at 3:01

Omkar Bhavare's user avatar

1

I tried all the stuff I found on the net (npm cache clear and rm -rf ~/.npm), but nothing seems to work. What solved the issue was updating node (and npm) to the latest version. Try that.

answered May 24, 2014 at 16:49

Nikola M.'s user avatar

Nikola M.Nikola M.

5736 silver badges16 bronze badges

In Windows I had a similar error.
Search paste App Data and search for the string npm.

I replaced the string 'npm' (including quotes) with 'npm.cmd' in both atlasboardlibpackage-dependency-manager.js and atlasboardlibclicommands.js. That fixed the problem.

Bob Gilmore's user avatar

Bob Gilmore

11.9k13 gold badges50 silver badges53 bronze badges

answered Oct 27, 2014 at 17:20

Vinicius Carvalho's user avatar

The same error during global install (npm install -g mymodule) for package with a non-existing script.

In package.json:

    ...
    "bin": {
      "module": "./bin/module"
    },
    ...

But the ./bin/module did not exist, as it was named modulejs.

answered Nov 3, 2014 at 12:40

hg.'s user avatar

hg.hg.

3241 silver badge13 bronze badges

0

  1. Install latest version of node
  2. Run: npm cache clean
  3. Run: npm install cordova -g

answered Jan 10, 2017 at 3:29

Dilhan Jayathilake's user avatar

You can get this error if your node.js is corrupted somehow as well. I fixed this error by uninstall/restart/install node.js completely and it fixed this error, along with the three other mysterious errors that are thrown.

answered May 26, 2018 at 4:04

Be careful with invalid values for keys «directories» and «files» in package.json

If you start with a new application, and you want to start completely blank, you have to
either start in a complete empty folder or have a valid package.json file in it.

If you do not want to create a package.json file first, just type: npm i some_package

Package with name «some_package» should be installed correctly in a new sub folder «node_modules».

If you create a package.json file first, type: npm init
Keep all the defaults (by just clicking ENTER), you should end up with a valid file.

It should look like this:

{
  "name": "yourfoldername",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

Note that the following keys are missing: «directories«, «repository» and «files«. It looks like if you use incorrect values for «directories» and/or «files«, you are not able to install the package. Leaving these keys out, solved the issue for me.

Also note key «main«. This one is present, but it does contain an invalid value. No file «index.js» exists (yet). You can safely remove it.

Now type: npm i some_package
and package with name «some_package» should be installed correctly in a new sub folder «node_modules».

answered Oct 16, 2018 at 13:16

RWC's user avatar

RWCRWC

4,4292 gold badges20 silver badges26 bronze badges

Had a similar error with npm in a docker container for webpack. The issue was caused by the —user command line argument of docker run, because the given user and group in there somehow messed up the rights on the local volume. Hope this helps someone 🙂

answered Mar 16, 2020 at 21:28

Hajo's user avatar

HajoHajo

8596 silver badges21 bronze badges

Tried nearly everything then finally this:

Simply remove node_modules then run 'npm install' again

answered May 3, 2020 at 15:08

Alex Stephens's user avatar

Alex StephensAlex Stephens

2,9071 gold badge35 silver badges41 bronze badges

I had the same problem on ubuntu, and got rid of the problem by closing the terminal and opening a new one.

answered Mar 3, 2021 at 11:50

abass.mahdavi's user avatar

1

It’s because there is no package.json and only package-lock.json

Try: npm init —yes

answered Jul 3, 2021 at 18:14

Rachel's user avatar

RachelRachel

892 silver badges8 bronze badges

I had a similar issue with a different cause: the yo node generator had added "files": ["lib/"] to my package.json and because my cli.js was outside of the lib/ directory, it was getting skipped when publishing to npm.

(Yeoman issue at https://github.com/yeoman/generator-node/issues/63 it should be fixed soon.)

answered Nov 6, 2014 at 16:51

Nathan Friedly's user avatar

Nathan FriedlyNathan Friedly

7,7693 gold badges39 silver badges59 bronze badges

I was getting the error «Error: ENOENT, stat ‘C:UsersuserNameAppDataRoamingnpm’. But there was no such directory. Created the directory and the npm install started working

answered Jan 29, 2015 at 2:39

k.iyengar's user avatar

I recently upgraded to node 4.2.1 on a Windows 7 x64 machine. When running

npm install -g bower

I got a similar error:

npm ERR! enoent ENOENT: no such file or directory, open ‘C:UsersTHE_USERNAMEAppDataLocalTempnpm-THE_HASH’

Thinking it was related to the AppData path, I played around with

npm config edit

and

npm config edit --global

to change the prefix, cache and tmp fields but received the same error with the new paths:

npm ERR! enoent ENOENT: no such file or directory, open ‘C:UsersTHE_USERNAMEnpm-tempnpm-THE_HASH’

All commands were run as Administrator, so I had full permissions.

Then I thought there were some issues with existing files so I ran:

npm cache clean

But got the same error. However, there were still some temp files lying around. Manually removing all temp data with cygwin finally fixed the problem for me:

rm -rf bower bower.cmd node_modules etc

If you only have Windows cmd, you could use something like

rmdir /S THE_TEMP_DIR

to remove all subdirectories (although if you have deeply nested node dependencies, this is notoriously problematic)

So, maybe there is some issues with upgrading npm and having versions of bower or other packages hanging around. In my case that seemed to be the problem

answered Oct 30, 2015 at 16:45

Andrew Johnston's user avatar

While installing ionic I got below error

115648 error enoent ENOENT: no such file or directory, rename
‘C:UsersUserNameAppDataRoamingnpmnode_modules.stagingansi-b11f0c4b’
-> ‘C:UsersUserNameAppDataRoamingnpmnode_modulesionicnode_modulescordova-libnode_modulesansi’

There was no folder called ansi at that path. I created it there and it installed correctly.

devlin carnate's user avatar

answered Jan 6, 2017 at 17:50

Vijay Mishra's user avatar

0

If you tried to «make install» in your project directory with this error you can try it:

rm -rf ./node_modules
npm cache clear
npm remove sails

then you can try to «make install»

If you have the «npm ERR! enoent ENOENT: no such file or directory, chmod ‘…/djam-backend/node_modules/js-beautify/js/bin/css-beautify.js'» then you can try to install some previous version of the js-beautify, more comments: https://github.com/beautify-web/js-beautify/issues/1247

"dependencies": {
  ...
  "js-beautify": "1.6.14"
  ...
}

and the run «make install». It seem works in case if you have not other dependencies that requires higher version (1.7.0) in this case you must downgrade this packages also in the packages.json.

or

answered Sep 18, 2017 at 10:29

Alex's user avatar

AlexAlex

1,2571 gold badge15 silver badges12 bronze badges

I am trying to globally install an npm module I just published. Every time I try to install, either from npm or the folder, I get this error.

npm ERR! Error: ENOENT, chmod '/usr/local/lib/node_modules/takeapeek/lib/cmd.js'
npm ERR! If you need help, you may report this log at:
npm ERR!     <http://github.com/isaacs/npm/issues>
npm ERR! or email it to:
npm ERR!     <npm-@googlegroups.com>

npm ERR! System Linux 3.8.0-19-generic
npm ERR! command "node" "/usr/local/bin/npm" "install" "-g" "takeapeek"
npm ERR! cwd /home/giodamlio
npm ERR! node -v v0.10.6
npm ERR! npm -v 1.3.6
npm ERR! path /usr/local/lib/node_modules/takeapeek/lib/cmd.js
npm ERR! code ENOENT
npm ERR! errno 34
npm ERR! 
npm ERR! Additional logging details can be found in:
npm ERR!     /home/giodamlio/npm-debug.log
npm ERR! not ok code 0

I am using sudo and I have triple checked everything in the package everything should work. I did some searching around, and saw a couple of similer cases none of which have been resolved. Here is what I tried.

  • Upgrade npm (sudo npm install -g npm)
  • Clear the global npm cache (sudo npm cache clear)
  • Clear the user npm cache (npm cache clear)

I noticed that the error had to do with the file I am linking to the path, specifically when npm tried to do a chmod. That shouldn’t be a problem, my lib/cli.js has normal permissions, and npm has superuser permissions during this install.

After digging through the npm docs I found an option that would stop npm from making the bin links(--no-bin-links), when I tried the install with it, it worked fine.

So what’s the deal? Is this some weird fringe case bug that has no solution yet?

Edit: For reference, here is the module I uploaded

mikemaccana's user avatar

mikemaccana

103k93 gold badges371 silver badges469 bronze badges

asked Aug 1, 2013 at 9:49

giodamelio's user avatar

9

Ok it looks like NPM is using your .gitignore as a base for the .npmignore file, and thus ignores /lib. If you add a blank .npmignore file into the root of your application, everything should work.

A better, more explicit approach is to use an allow-list rather than a disallow-list, and use the «files» field in package.json to specify the files in your package.

[edit] — more info on this behaviour here: https://docs.npmjs.com/cli/v7/using-npm/developers#keeping-files-out-of-your-package

answered Aug 2, 2013 at 15:03

badsyntax's user avatar

badsyntaxbadsyntax

9,2553 gold badges45 silver badges65 bronze badges

10

I ran into a similar problem,

npm cache clean

solved it.

Uri Agassi's user avatar

Uri Agassi

36.5k13 gold badges76 silver badges93 bronze badges

answered May 3, 2014 at 15:06

Genjuro's user avatar

GenjuroGenjuro

7,2657 gold badges39 silver badges61 bronze badges

2

This problem somehow arose for me on Mac when I was trying to run npm install -g bower. It was giving me a number of errors for not being able to find things like graceful-fs. I’m not sure how I installed npm originally, but it looks like perhaps it came down with node using homebrew. I first ran

brew uninstall node

This removed both node and npm from my path. From there I just reinstalled it

brew install node

When it completed I had node and npm on my path and I was able to run

rm -rf ~/.npm
npm install -g bower

This then installed bower successfully.

Updating the brew formulas and upgrading the installs didn’t seem to work for me, I’m not sure why. The removal of the .npm folder was something that had worked for other people, and I had tried it without success. I did it this time just in case. Note also that neither of the following solved the problem for me, although it did for others:

npm cache clean
sudo npm cache clean

answered Jan 9, 2014 at 23:52

user1978019's user avatar

user1978019user1978019

2,8081 gold badge28 silver badges37 bronze badges

0

I encountered similar behavior after upgrading to npm 6.1.0. It seemed to work once, but then I got into a state with this error while trying to install a package that was specified by path on the filesystem:

npm ERR! code ENOENT
npm ERR! errno -2
npm ERR! syscall rename

The following things did not fix the problem:

  • rm -rf node_modules
  • npm cache clean (gave npm ERR! As of npm@5, the npm cache self-heals….use 'npm cache verify' instead.)
  • npm cache verify
  • rm -rf ~/.npm

How I fixed the problem:

  • rm package-lock.json

answered Jul 12, 2018 at 12:50

Ian's user avatar

IanIan

10.8k2 gold badges35 silver badges57 bronze badges

I was getting this error on npm install and adding .npmignore did not solve it.

Error: ENOENT, stat ‘C:UsersMy-UserNameAppDataRoamingnpm’

I tried going to the mentioned folder and it did not exist.
The error was fixed when I created npm folder in Roaming folder.

This is on Windows 8.1

answered Nov 15, 2014 at 23:08

Vijay Vepakomma's user avatar

I had the same problem, and just found a handling not mentioned here. Though I’d contribute to the community:

npm install -g myapp was not copying the bin directory. I found this to be because I did not include it in the files in my package.json

"files": [
  "lib",
  "bin" // this was missing
]

answered Jun 11, 2015 at 0:26

dthree's user avatar

dthreedthree

19.2k14 gold badges75 silver badges105 bronze badges

3

Delete package-lock.json file then run npm install

answered Apr 13, 2021 at 6:00

Clark's user avatar

ClarkClark

1391 silver badge11 bronze badges

I was getting a similar error on npm install on a local installation:

npm ERR! enoent ENOENT: no such file or directory, stat '[path/to/local/installation]/node_modules/grunt-contrib-jst'

I am not sure what was causing the error, but I had recently installed a couple of new node modules locally, upgraded node with homebrew, and ran ‘npm update -g’.

The only way I was able to resolve the issue was to delete the local node_modules directory entirely and run npm install again:

cd [path/to/local/installation]
npm rm -rdf node_modules
npm install

answered Dec 31, 2015 at 0:40

g.carey's user avatar

g.careyg.carey

6807 silver badges6 bronze badges

I have a similar problem specifucally :
ERR! enoent ENOENT: no such file or directory, chmod ‘node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/bin/sshpk-conv
I tried all above solutions but no luck.
I was using vagrant box, and the project was in a shared folder. The problems seems to be only there, when I move the project to another not shared folder (woth host), voila! problem solved.
Just in case another person was using also vagrant

answered Mar 2, 2017 at 21:05

joaco1977's user avatar

1

I got the simple solution, just clear the npm cache.

sudo npm cache clear --force

then remove the node_modules & package-lock.json

sudo rm -rf node_modules
sudo rm -rf package-lock.json

Now install the dependencies module using npm and start the server

npm install && npm start

answered Jul 17, 2021 at 2:38

Abhishek Patel's user avatar

I got a similar error message when trying to npm install a bunch of dependencies. Turns out some of them fail to install on Debian/Ubuntu because they expect /usr/bin/node to be the node executable. To fix, you need do

sudo ln -s nodejs /usr/bin/node 

or better yet,

sudo apt-get install nodejs-legacy

For more info: https://stackoverflow.com/a/21171188/7581

Community's user avatar

answered Feb 19, 2015 at 6:26

itsadok's user avatar

itsadokitsadok

28.5k29 gold badges124 silver badges170 bronze badges

I got this error while trying to install a grunt plugin. i found i had an outdated version of npm and the error went away after updating npm to the latest version

npm install -g npm

answered Apr 4, 2015 at 16:13

Prabhu Murthy's user avatar

Prabhu MurthyPrabhu Murthy

8,9615 gold badges28 silver badges36 bronze badges

I think your compiled coffee script is missing from the published npm package. Try writing a prepublish command.

answered Aug 1, 2013 at 23:34

leeway's user avatar

leewayleeway

4751 gold badge3 silver badges8 bronze badges

2

In my case (multiple code ENOENT errno 34) problem was with ~/.npm/ directory access. Inside it there were some subdirs having root:root rights, which were causing problems while I run commands as normal user (without sudo). So I changed ownership of all subdirs and files inside ~/.npm/ dir into my local user and group. That did the trick on my Ubuntu (on Mac should work too).

$ sudo chown yourusername.yourgroupname ~/.npm/ -R

You should know your user name, right? If no then run $ whoami and substitute your group name with it too, like this:

$ sudo chown johnb.johnb ~/.npm/ -R

EDIT:

Test case:

From my local account /home/johnb I npm-installed globally some generator for yeoman, like this:

$ sudo npm install -g generator-laravel

Problem nature:

Above action caused some dependencies being installed inside ~/.npm/ dir, having root:root ownership (because of sudo ...). Evidently npm does not run as local user (or change dependencies subdirs ownership afterwards) when pulling dependencies and writing them to a local user subdir ~/.npm/.
As long as npm would be so careless against fundamental unix filesystem security issues the problem would reoccur.

Solution:

  1. Continuosly check if ~/.npm/ contains subdirs with ownership (and/or permissions) other than your local user account, especially when you install or update something with sodo (root). If so, change the ownership inside ~/.npm/ to a local user recursively.

  2. Ask npm, bower, grunt, ... community that they address this issue as I described it above.

answered May 28, 2014 at 22:10

paperclip's user avatar

Had a similar Issue but I was in wrong directory please cross check the path of thee file & the run npm start

answered May 2, 2022 at 3:01

Omkar Bhavare's user avatar

1

I tried all the stuff I found on the net (npm cache clear and rm -rf ~/.npm), but nothing seems to work. What solved the issue was updating node (and npm) to the latest version. Try that.

answered May 24, 2014 at 16:49

Nikola M.'s user avatar

Nikola M.Nikola M.

5736 silver badges16 bronze badges

In Windows I had a similar error.
Search paste App Data and search for the string npm.

I replaced the string 'npm' (including quotes) with 'npm.cmd' in both atlasboardlibpackage-dependency-manager.js and atlasboardlibclicommands.js. That fixed the problem.

Bob Gilmore's user avatar

Bob Gilmore

11.9k13 gold badges50 silver badges53 bronze badges

answered Oct 27, 2014 at 17:20

Vinicius Carvalho's user avatar

The same error during global install (npm install -g mymodule) for package with a non-existing script.

In package.json:

    ...
    "bin": {
      "module": "./bin/module"
    },
    ...

But the ./bin/module did not exist, as it was named modulejs.

answered Nov 3, 2014 at 12:40

hg.'s user avatar

hg.hg.

3241 silver badge13 bronze badges

0

  1. Install latest version of node
  2. Run: npm cache clean
  3. Run: npm install cordova -g

answered Jan 10, 2017 at 3:29

Dilhan Jayathilake's user avatar

You can get this error if your node.js is corrupted somehow as well. I fixed this error by uninstall/restart/install node.js completely and it fixed this error, along with the three other mysterious errors that are thrown.

answered May 26, 2018 at 4:04

Be careful with invalid values for keys «directories» and «files» in package.json

If you start with a new application, and you want to start completely blank, you have to
either start in a complete empty folder or have a valid package.json file in it.

If you do not want to create a package.json file first, just type: npm i some_package

Package with name «some_package» should be installed correctly in a new sub folder «node_modules».

If you create a package.json file first, type: npm init
Keep all the defaults (by just clicking ENTER), you should end up with a valid file.

It should look like this:

{
  "name": "yourfoldername",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

Note that the following keys are missing: «directories«, «repository» and «files«. It looks like if you use incorrect values for «directories» and/or «files«, you are not able to install the package. Leaving these keys out, solved the issue for me.

Also note key «main«. This one is present, but it does contain an invalid value. No file «index.js» exists (yet). You can safely remove it.

Now type: npm i some_package
and package with name «some_package» should be installed correctly in a new sub folder «node_modules».

answered Oct 16, 2018 at 13:16

RWC's user avatar

RWCRWC

4,4292 gold badges20 silver badges26 bronze badges

Had a similar error with npm in a docker container for webpack. The issue was caused by the —user command line argument of docker run, because the given user and group in there somehow messed up the rights on the local volume. Hope this helps someone 🙂

answered Mar 16, 2020 at 21:28

Hajo's user avatar

HajoHajo

8596 silver badges21 bronze badges

Tried nearly everything then finally this:

Simply remove node_modules then run 'npm install' again

answered May 3, 2020 at 15:08

Alex Stephens's user avatar

Alex StephensAlex Stephens

2,9071 gold badge35 silver badges41 bronze badges

I had the same problem on ubuntu, and got rid of the problem by closing the terminal and opening a new one.

answered Mar 3, 2021 at 11:50

abass.mahdavi's user avatar

1

It’s because there is no package.json and only package-lock.json

Try: npm init —yes

answered Jul 3, 2021 at 18:14

Rachel's user avatar

RachelRachel

892 silver badges8 bronze badges

I had a similar issue with a different cause: the yo node generator had added "files": ["lib/"] to my package.json and because my cli.js was outside of the lib/ directory, it was getting skipped when publishing to npm.

(Yeoman issue at https://github.com/yeoman/generator-node/issues/63 it should be fixed soon.)

answered Nov 6, 2014 at 16:51

Nathan Friedly's user avatar

Nathan FriedlyNathan Friedly

7,7693 gold badges39 silver badges59 bronze badges

I was getting the error «Error: ENOENT, stat ‘C:UsersuserNameAppDataRoamingnpm’. But there was no such directory. Created the directory and the npm install started working

answered Jan 29, 2015 at 2:39

k.iyengar's user avatar

I recently upgraded to node 4.2.1 on a Windows 7 x64 machine. When running

npm install -g bower

I got a similar error:

npm ERR! enoent ENOENT: no such file or directory, open ‘C:UsersTHE_USERNAMEAppDataLocalTempnpm-THE_HASH’

Thinking it was related to the AppData path, I played around with

npm config edit

and

npm config edit --global

to change the prefix, cache and tmp fields but received the same error with the new paths:

npm ERR! enoent ENOENT: no such file or directory, open ‘C:UsersTHE_USERNAMEnpm-tempnpm-THE_HASH’

All commands were run as Administrator, so I had full permissions.

Then I thought there were some issues with existing files so I ran:

npm cache clean

But got the same error. However, there were still some temp files lying around. Manually removing all temp data with cygwin finally fixed the problem for me:

rm -rf bower bower.cmd node_modules etc

If you only have Windows cmd, you could use something like

rmdir /S THE_TEMP_DIR

to remove all subdirectories (although if you have deeply nested node dependencies, this is notoriously problematic)

So, maybe there is some issues with upgrading npm and having versions of bower or other packages hanging around. In my case that seemed to be the problem

answered Oct 30, 2015 at 16:45

Andrew Johnston's user avatar

While installing ionic I got below error

115648 error enoent ENOENT: no such file or directory, rename
‘C:UsersUserNameAppDataRoamingnpmnode_modules.stagingansi-b11f0c4b’
-> ‘C:UsersUserNameAppDataRoamingnpmnode_modulesionicnode_modulescordova-libnode_modulesansi’

There was no folder called ansi at that path. I created it there and it installed correctly.

devlin carnate's user avatar

answered Jan 6, 2017 at 17:50

Vijay Mishra's user avatar

0

If you tried to «make install» in your project directory with this error you can try it:

rm -rf ./node_modules
npm cache clear
npm remove sails

then you can try to «make install»

If you have the «npm ERR! enoent ENOENT: no such file or directory, chmod ‘…/djam-backend/node_modules/js-beautify/js/bin/css-beautify.js'» then you can try to install some previous version of the js-beautify, more comments: https://github.com/beautify-web/js-beautify/issues/1247

"dependencies": {
  ...
  "js-beautify": "1.6.14"
  ...
}

and the run «make install». It seem works in case if you have not other dependencies that requires higher version (1.7.0) in this case you must downgrade this packages also in the packages.json.

or

answered Sep 18, 2017 at 10:29

Alex's user avatar

AlexAlex

1,2571 gold badge15 silver badges12 bronze badges

Errors

  • Сломанная установка npm
  • Random errors
  • Не найдена совместимая версия
  • Permissions errors
  • Error: ENOENT, stat 'C:Users<user>AppDataRoamingnpm' в Windows 7
  • No space
  • No git
  • Запуск блока Vagrant на Windows не удается из-за проблем с длиной пути
  • npm использует только git: и ssh+git: URL-адреса для репозиториев GitHub, нарушая прокси
  • SSL error
  • SSL-intercepting proxy
  • Не найдено/Ошибка сервера
  • Invalid JSON
  • Многие ошибки ENOENT / ENOTEMPTY в выводе
  • cb() never called! при использовании термоусадочных зависимостей
  • ошибки при входе в npm
  • npm зависает в Windows на addRemoteTarball
  • npm не запускает последнюю версию на машине с Windows

Сломанная установка npm

Если ваш npm сломан:

  • На Mac или Linux переустановите npm .
  • Windows: если вы используете Windows и у вас не работает установка, проще всего переустановить узел из официального установщика (см. Это примечание об установке последней стабильной версии ).

Random errors

  • Некоторые странные проблемы можно решить, просто запустив npm cache clean и повторив попытку.
  • Если у вас возникли проблемы с npm install , используйте параметр -verbose , чтобы увидеть более подробную информацию.

Не найдена совместимая версия

У вас устаревший npm. Пожалуйста, обновите npm до последней стабильной версии .

Permissions errors

См. Обсуждения в разделах « Загрузка и установка Node.js и npm » и « Устранение ошибок разрешений EACCES при глобальной установке пакетов », чтобы узнать, как избежать и устранить ошибки разрешений.

Error: ENOENT, stat 'C:Users<user>AppDataRoamingnpm' в Windows 7

Ошибка Error: ENOENT, stat 'C:Users<user>AppDataRoamingnpm' в Windows 7 является следствием joyent / node # 8141 и является проблемой установщика Node для Windows. Обходной путь — убедиться, что C:Users<user>AppDataRoamingnpm существует и доступен для записи с вашей обычной учетной записью.

No space

npm ERR! Error: ENOSPC, write

Вы пытаетесь установить диск,на котором либо нет места,либо нет разрешения на запись.

  • Освободите место на диске или
  • Установите папку tmp где-нибудь с большим пространством: npm config set tmp /path/to/big/drive/tmp или
  • Соберите Node самостоятельно и установите его где-нибудь,где есть место для записи с большим количеством места.

No git

npm ERR! not found: git
ENOGIT

Вам необходимо установить git . Или вам может потребоваться добавить информацию о git в свой профиль npm. Вы можете сделать это из командной строки или на веб-сайте. Для получения дополнительной информации см. « Управление настройками вашего профиля ».

Запуск блока Vagrant на Windows не удается из-за проблем с длиной пути

@drmyersii прошел через много мучительных проб и ошибок, чтобы предложить рабочее решение, включающее длинные пути Windows и некоторую настраиваемую конфигурацию Vagrant:

Это коммит, в котором я его реализовал , но я опубликую здесь основной фрагмент кода:

config.vm.provider "virtualbox" do |v|
    v.customize ["sharedfolder", "add", :id, "--name", "www", "--hostpath", (("//?/" + File.dirname(__FILE__) + "/www").gsub("/","\"))]
end

config.vm.provision :shell, inline: "mkdir /home/vagrant/www"
config.vm.provision :shell, inline: "mount -t vboxsf -o uid=`id -u vagrant`,gid=`getent group vagrant | cut -d: -f3` > www /home/vagrant/www", run: "always"

В приведенном выше коде я добавляю \? К абсолютному пути текущего каталога. Это фактически заставит Windows API разрешить увеличение переменной MAX_PATH (обычно не более 260). Подробнее о максимальном пути . Это происходит во время создания общей папки, которая намеренно обрабатывается VBoxManage, а не методом Vagrant «synced_folder». Последний пункт довольно понятен; мы создаем новую общую папку, а затем убеждаемся, что она монтируется каждый раз, когда к машине обращаются или касаются, поскольку Vagrant любит перезагружать свои монтированные / общие папки при каждой загрузке.

npm использует только git: и ssh+git: URL-адреса для репозиториев GitHub, нарушая прокси

@LaurentGoderre исправил это с помощью некоторых уловок Git :

Я исправил эту проблему для нескольких своих коллег,запустив следующие две команды:

git config --global url."https://github.com/".insteadOf git@github.com:
git config --global url."https://".insteadOf git:

Одна вещь, которую мы заметили, заключается в том, что используемый .gitconfig не всегда является ожидаемым, поэтому, если вы находитесь на машине, которая изменила домашний путь к общему диску, вам необходимо убедиться, что ваш .gitconfig одинаков как на вашем общем диске, так и на в c:users[your user]

SSL Error

npm ERR! Error: 7684:error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol:opensslssls23_clnt.c:787:

Вы пытаетесь подключить SSL к незашифрованной конечной точке. Чаще всего это связано с ошибкой конфигурации прокси (см. также это полезное, хотя и устаревшее, руководство ). В этом случае вам не нужно отключать strict-ssl — вам может понадобиться настроить файл CA/CA для использования с вашим прокси, но гораздо лучше потратить время на то, чтобы разобраться в этом, чем отключать защиту SSL.

npm ERR! Error: SSL Error: CERT_UNTRUSTED
npm ERR! Error: SSL Error: UNABLE_TO_VERIFY_LEAF_SIGNATURE

Эта проблема может возникнуть, если вы используете Node 0.6. Пожалуйста, обновите до версии 0.8 или выше. Подробности смотрите в этом посте .

Вы также можете попробовать следующие обходные пути: npm config set ca "" или npm config set strict-ssl false

npm ERR! Error: SSL Error: SELF_SIGNED_CERT_IN_CHAIN

npm больше не поддерживает самоподписанные сертификаты

Either:

  • обновите свою версию npm npm install npm -g --ca=""
  • указать вашей текущей версии npm использовать известных регистраторов npm config set ca=""

Если это не решит проблему, возможно, у вас прокси для перехвата SSL. (Например, https://github.com/npm/npm/issues/7439#issuecomment-76024878 )

SSL-intercepting proxy

Неразрешенный. См. Https://github.com/npm/npm/issues/9282

Не найдено/Ошибка сервера

npm http 404 https:
npm ERR! fetch failed https:
npm ERR! Error: 404 Not Found
npm http 500 https://registry.npmjs.org/phonegap
  • Скорее всего, это временный сбой реестра npm. Проверьте статус сервера npm и повторите попытку позже.
  • Если ошибка сохраняется,возможно,опубликованный пакет поврежден.Свяжитесь с владельцем пакета и попросите его опубликовать новую версию пакета.

Invalid JSON

npm ERR! SyntaxError: Unexpected token <
npm ERR! registry error parsing json
  • Возможный временный сбой реестра npm или поврежденный кеш локального сервера. Запустите npm cache clean и / или повторите попытку позже.
  • Это может быть вызвано корпоративными прокси, которые дают HTML-ответы на запросы package.json . Проверьте конфигурацию прокси-сервера npm .
  • Убедитесь, что это не проблема с пакетом, который вы пытаетесь установить (например, недопустимый package.json ).

Многие ошибки ENOENT / ENOTEMPTY в выводе

npm написан для эффективного использования ресурсов при установке, и отчасти это связано с тем, что он пытается делать столько вещей одновременно, сколько это возможно. Иногда это приводит к состояниям гонки и другим проблемам синхронизации. Начиная с npm 2.0.0, было решено очень большое количество этих проблем. Если в выводе журнала вы видите ENOENT lstat , ENOENT chmod , ENOTEMPTY unlink или что-то подобное, попробуйте обновить npm до последней версии. Если проблема не исчезнет, ​​посмотрите npm / npm # 6043 и посмотрите, обсуждал ли кто-нибудь вашу проблему.

cb() never called! при использовании термоусадочных зависимостей

Взгляните на выпуск # 5920 .Мы работаем над исправлением этого, но это довольно сложное состояние гонки, и это отнимает у нас немного времени. Вы можете попробовать переместить файл npm-shrinkwrap.json в сторону, пока мы не исправим это.Это было исправлено в версиях npm новее, чем npm@2.1.5 , поэтому обновите до npm@latest .

npm login ошибки входа в npm

Иногда npm login завершается неудачно без очевидной причины. Первое, что нужно сделать, это войти в систему на https://www.npmjs.com/login и убедиться, что ваш адрес электронной почты на npmjs.com совпадает с адресом электронной почты, который вы указываете для npm login в npm .

Если проблема не в этом или вы видите сообщение "may not mix password_sha and pbkdf2" , то

  1. Авторизуйтесь на https://npmjs.com/
  2. Смените пароль на https://npmjs.com/password — вы даже можете «сменить» его на тот же пароль
  3. Очистите поля, связанные с входом в систему, из ~/.npmrc , например, запустив sed -ie '/registry.npmjs.org/d' ~/.npmrc
  4. npm login

и в целом,похоже,это работает.

Историю этой проблемы см. На https://github.com/npm/npm/issues/6641#issuecomment-72984009 .

npm зависает в Windows на addRemoteTarball

Проверьте, установлены ли в вашем .npmrc два временных каталога :

Найдите строки, определяющие переменную конфигурации tmp . Если вы найдете более одного, удалите все, кроме одного.

См. Https://github.com/npm/npm/issues/7590 для получения дополнительной информации об этой необычной проблеме.

npm не запускает последнюю версию на машине с Windows

См. Раздел о Windows здесь .

Необходимо определиться с версией, которая вам нужна. Я предпочитаю ставить не новейшую версию Node.js, а последнюю LTS.

Установка в Elementary OS, Ubuntu:

curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash -
sudo apt-get install -y nodejs

Установка в Debian:

curl -sL https://deb.nodesource.com/setup_14.x | bash -
apt-get install -y nodejs

Инструкции под разные системы и для разных версий от разработчиков.

Проверка версий:

nodejs -v
npm -v

Если для проекта вы делаете:

npm install

И вылезает ошибка, вроде:

gyp ERR! build error 
gyp ERR! stack Error: `make` failed with exit code: 2
gyp ERR! stack     at ChildProcess.onExit (/home/.../node_modules/node-gyp/lib/build.js:262:23)
gyp ERR! stack     at ChildProcess.emit (events.js:311:20)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:275:12)
gyp ERR! System Linux 5.3.0-42-generic
gyp ERR! command "/usr/bin/node" "/home/.../node_modules/node-gyp/bin/node-gyp.js" "rebuild" "--verbose" "--libsass_ext=" "--libsass_cflags=" "--libsass_ldflags=" "--libsass_library="
gyp ERR! cwd /home/.../node_modules/node-sass
gyp ERR! node -v v12.16.1
gyp ERR! node-gyp -v v3.8.0
gyp ERR! not ok 
Build failed with error code: 1
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.4 (node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.4: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! node-sass@4.10.0 postinstall: `node scripts/build.js`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the node-sass@4.10.0 postinstall script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/d1mon/.npm/_logs/2020-03-31T05_52_52_174Z-debug.log

Необходимо удалить каталог node_modules и файл блокировки package-lock.json, очистить кэш и пробовать заново:

rm -rf node_modules package-lock.json
npm cache clean --force
npm install

Глобальная установка пакетов

Для глобальной установки пакетов в команду добавляется параметр -g. Но это не будет работать по умолчанию из-за проблем с правами доступа, поэтому предварительно требуется сделать следующее.

Создадим каталог для глобальных установок:

mkdir ~/.npm-global

Настройка npm на использование нового каталога:

npm config set prefix '~/.npm-global'

В файл ~/.profile необходимо добавить строку:

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

В командной строке снова, для применения изменений:

source ~/.profile

На этом все, теперь можно устанавливать пакеты глобально.

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

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Not configured to listen on any interfaces dhcp ошибка
  • Not another pdf scanner 2 ошибка драйвера сканирования