2

My Node.js project has a directory structure like so:

  • server.js
  • package.json
  • ...
  • public
    • app.js
    • index.html

A call to require() works fine in server.js, but when I attempt to require a package in app.js, a ReferenceError is thrown:

 require is not defined at app.js:1

How do I require a node module from a file that is not in the global scope of my project?

Blake Allen
  • 347
  • 1
  • 10

1 Answers1

5

Use some thing like this var db = require('../model/db');

It basically means ../ moving one step up from the current directory then into model and then to db.

You need to use this to move up the directory structure and then use that in require .

node.js is a server-side Javascript execution environment that combines the V8 Javascript engine with a bunch of server-side libraries. require() is one such feature that node.js adds to the environment. So, when you run node in the terminal, you are running an environment that contains require().

require() is not a feature that is built into the browser. That is a specific feature of node.js, not of a browser. So, when you try to have the browser run your script, it does not have require().

In order to use Require Js . Just follow this link

Rahul Singh
  • 19,030
  • 11
  • 64
  • 86
  • 2
    The problem is not the path. It's that `require` is not defined – blex Aug 17 '17 at 18:20
  • @blex if that is the problem then how come it works in server.js ? – Rahul Singh Aug 17 '17 at 18:23
  • 2
    `server.js` runs in NodeJS. `app.js` runs in the browser (since it's in the `public` folder). So, in order to be able to use `require` in the browser, he needs to load the [RequireJS](http://requirejs.org/) library on the page. Then, he needs to make the node modules available to the browser [like this](https://stackoverflow.com/a/27464258/1913729). I'm not posting this as an answer as I'm not sure if other steps are required, but that seems logical to me. – blex Aug 17 '17 at 18:25
  • this is a thing that just stuck my mind @blex. Thanks just overlooked .updated the answer for the quote , you might even answer this as it was your idea it stuck me later – Rahul Singh Aug 17 '17 at 18:26
  • If @blex does not answer, can you please mention RequireJS in your answer as a solution? – Blake Allen Aug 17 '17 at 18:30
  • 2
    @BlakeAllen i have updated the require js link it has the steps how to use it in node js . i think that will work for you . – Rahul Singh Aug 17 '17 at 18:34