Reputation: 375
I have installed 'node.js' and then executed 'npm install mqtt' from 'node.js' command line to install 'mqtt.js'. Now to test 'mqtt client' I am trying to execute : var mqtt = require('mqtt'); which results in error saying:
"Error: Cannot find module 'mqtt'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at repl:1:12
at REPLServer.self.eval (repl.js:110:21)
at repl.js:249:20
at REPLServer.self.eval (repl.js:122:7)
at Interface.<anonymous> (repl.js:239:12)
at Interface.EventEmitter.emit (events.js:95:17)"
Upvotes: 3
Views: 11697
Reputation: 59
When you use the command line for node.js, it searches for node modules that are installed globally which is usually in the directory /usr/lib/node_modules in Linux machines.
When you run npm install, the node modules are installed locally in the same directory where the node terminal was launched.
If you want to access node modules in the node terminal, you need to run npm install mqtt -g where -g stands for global installation.
Usually Linux machines don't allow normal users to access /usr/lib/node_modules so it'll be better to run it as sudo npm install mqtt -g
Upvotes: 0
Reputation: 5043
This is a common issue that Node developers face. While working on Unix systems, sometimes it may not allow you to install such packages. For that, you will need sudo
permissions. Sometimes, the package is installed but only in your local modules, and when you try to import it from outside of the directory, the error occurs. Sometimes, your compiler read your dependencies, but not able to find this package in that, at that time also you face this error.
Anyways, don't worry. You just have to follow some steps below.
initialize
your project using npm init
before starting development. This will initialize your project and generate package.json
file.Then, if you want any library as dependencies, try --save
with npm install
command. This will save your dependency in package.json
file.
e.g. npm install mqtt --save
If any package is not found after installing, install it globally by -g
flag.
Globally installed packages will be accessible within your system. e.g. npm install mqtt -g
.
Note: Unix system needs SUDO
permission for installing it globally.
I hope this will help you.
Upvotes: 0
Reputation: 46
First, you need to add the MQTT library.
If you have npm package manager installed on the server, you should run npm install mqtt --save
For detailed information: https://www.npmjs.com/package/mqtt
Upvotes: 3
Reputation: 51
For requiring Node.js module, refer to this tutorial which is pretty detailed.
http://www.bennadel.com/blog/2169-where-does-node-js-and-require-look-for-modules.htm
By the way, createClient()
has been deprecated by mqtt module, use connect()
instead.
If you ever want to test your MQTT client with a ready online broker, try http://www.robomq.io.
Upvotes: 2