NodeJS:cannot find module 'socket.io' | nmp全局安装 modules 后在应用中 require 不到的解决方案

Windows环境下, 通过 npm install -g 安装的全局模块, 可能无法在app中被require引用到, 怎么办?

其实, 只要设置环境变量 NODE_PATH 指向全局模块根目录即可. 我的解决方法是:

我的电脑->属性-> 高级-> 环境变量, 添加一个环境变量名为 NODE_PATH , 将其值设置为全局模块的根目录. 

我这里这个目录是: C:\Program Files\nodejs\node_modules 


目录结构如下:

NodeJS:cannot find module 'socket.io' | nmp全局安装 modules 后在应用中 require 不到的解决方案_第1张图片


socket.js代码如下:

// 引入需要的模块:http和socket.io
var http = require('http'), io = require('socket.io');
//创建server
var server = http.createServer(function(req, res){ 
  // Send HTML headers and message
  res.writeHead(200,{ 'Content-Type': 'text/html' }); 
  res.end('

Hello Socket Lover!

'); }); //端口9999 server.listen(9999); //创建socket var socket = io.listen(server); //添加连接监听 socket.on('connection', function(client){ //连接成功则执行下面的监听 client.on('message',function(event){ console.log('Received message from client!',event); }); //断开连接callback client.on('disconnect',function(){ console.log('Server has disconnected'); }); });


配置好环境变量  执行 node socket.js成功..

NodeJS:cannot find module 'socket.io' | nmp全局安装 modules 后在应用中 require 不到的解决方案_第2张图片

你可能感兴趣的:(nodeJs)