node.js websocket模块安装但不能在脚本中工作

Sup*_*ast 9 websocket node.js

我刚刚安装了node.js + microsoft visual以便能够安装websocket,它安装得很好:

C:\Users\Administrator>npm install websocket
npm http GET https://registry.npmjs.org/websocket
npm http 304 https://registry.npmjs.org/websocket

> websocket@1.0.8 install C:\Users\Administrator\node_modules\websocket
> node install.js

[websocket v1.0.8] Attempting to compile native extensions.
[websocket v1.0.8] Native extension compilation successful!
websocket@1.0.8 node_modules\websocket

C:\Users\Administrator>
Run Code Online (Sandbox Code Playgroud)

现在我正在尝试运行一个脚本:

   var WebSocketServer = require('websocket').Server;
Run Code Online (Sandbox Code Playgroud)

而我得到了这个:

C:\Users\Administrator>node C:\server\src\main.js

module.js:340
throw err;
      ^
Error: Cannot find module 'websocket'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Module.require (module.js:362:17)
at require (module.js:378:17)
at Object.<anonymous> (C:\server\src\main.js:2:23)
at Module._compile (module.js:449:26)
at Object.Module._extensions..js (module.js:467:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.runMain (module.js:492:10)

C:\Users\Administrator>
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激,我已经尝试过多次安装,我尝试全局安装(-g标签).

Dre*_*kes 7

请注意,如果您全局安装了NPM模块(使用该-g选项)并且未告知node使用全局模块路径来解决需求,则可能会出现此错误.

在Linux上我websocket全局安装了模块:

$ sudo npm install -g websocket
npm http GET https://registry.npmjs.org/websocket
npm http 200 https://registry.npmjs.org/websocket
npm http GET https://registry.npmjs.org/websocket/-/websocket-1.0.8.tgz
npm http 200 https://registry.npmjs.org/websocket/-/websocket-1.0.8.tgz

> websocket@1.0.8 install /usr/local/lib/node_modules/websocket
> node install.js

[websocket v1.0.8] Attempting to compile native extensions.
[websocket v1.0.8] Native extension compilation successful!
websocket@1.0.8 /usr/local/lib/node_modules/websocket
Run Code Online (Sandbox Code Playgroud)

接下来我必须导出NODE_PATH环境变量以指向上面输出中提到的路径:

export NODE_PATH=/usr/local/lib/node_modules
Run Code Online (Sandbox Code Playgroud)

在这之后:

$ node
> require('websocket')
{ server: 
   { [Function: WebSocketServer]
     super_: { [Function: EventEmitter] listenerCount: [Function] } },
     ...
Run Code Online (Sandbox Code Playgroud)

希望这有助于搜索此错误消息的人.


Fil*_*zzi 5

我在这里遇到了同样的错误..我按照以下步骤操作:

以管理员身份执行cmd(右键cmd图标->以管理员身份运行)然后输入cmd:

c:\Node Instalation Dir\> npm install -g express
c:\Node Instalation Dir\> npm install websocket --force
Run Code Online (Sandbox Code Playgroud)

现在你可以运行你的脚本:

c:\Node Instalation Dir\> node script.js
Run Code Online (Sandbox Code Playgroud)

我在测试服务器上做了.. 尽量不要在生产服务器中使用“--force”好吗?


Ray*_*hih 1

npm 将模块安装在./node_modules/. 所以你应该.C:\server\src\