1

I have installed a package using 'npm install package-name' and now I am wondering how I can use this package in my global.js file which is in the public/javascripts folder?

I have tried using 'var name = require('package-name');' in the global.js file however this does not seem to be working. Am I meant to reference the package some place else?

Any help would be appreciated. Thank you.

2
  • Posting some code, with any error messages would be useful. Commented Jul 10, 2014 at 2:30
  • Please look at my response for the below answer. Thank you for your response. Commented Jul 10, 2014 at 9:39

1 Answer 1

1

So the short answer is use the browserify. Really understanding all the implications of sharing code between node and the browser is somewhat of a lengthy topic, so please take the time to read the tutorials and the handbook. But the basic idea is

  • in your global.js file, load the module from node with var name = require("package-name"); as you are doing.
  • Transform your file with browserify a la browserify public/javascripts/global.js > public/javascripts/main.js
  • change your HTML <script> tag to load the new main.js file.
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for your reply! I have installed browserify and transformed my global.js to the main.js and changed the html script reference to the new main.js. However, I am getting the "Cannot find module kmeans" error. I have installed the package 'node-kmeans' and it is in my 'node_modules' folder and I am trying to reference the 'node-kmeans/lib/kmeans.js' file by using 'var kmeans = require('kmeans'). Is there anything I am doing wrong?
Use require("node-kmeans"); the name you pass to require is the same name you passed to npm install
I have tried that as well but I am getting the same error "Cannot find module node-kmeans"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.