14

I have an index.jade in my 'views' folder.

doctype html
html
  head
    title= title
    link(rel='stylesheet', href='/stylesheets/main.css')
    script(src='../node_modules/some_package/package_script.min.js')

I have index.js in my routes folder with a router:

router.get('/', function(req, res) {
  res.render('index', { title: 'title goes here' })
});

I keep getting a 404 error when I try to access the node_modules folder in the jade file in the console: GET /node_modules/some_package/package_script.min.js 404 1ms - 19b

How exactly does the file pathing work / how can I fix it for Express when I'm trying to access a script in the node_modules? Do I need to copy the necessary javascript files and place them under the 'javascripts' folder under 'public' for it to work?

Thanks!

Bryan
  • 1,438
  • 3
  • 15
  • 24

1 Answers1

21

Whoa! Hold on... node_modules is a private directory and shouldn't be exposed. By default the public directory is the public root path for static files:

app.use(express.static(path.join(__dirname, 'public')));

In there is a javascripts directory. Copy your script there and change the src attribute in your template to:

/javascripts/package_script.min.js

If you really wanted to serve up node_modules, which would be a bad idea, add the following beneath the app.use(express.static(...)); line above:

app.use(express.static(path.join(__dirname, 'node_modules')));
Matthew Rankin
  • 457,139
  • 39
  • 126
  • 163
a_arias
  • 3,036
  • 2
  • 21
  • 20
  • 1
    Brilliant answer. Had a gut feeling there was something wrong. Thanks for clarifying that node_modules is a private directory, a big no-no! [No-no information](http://stackoverflow.com/questions/24397379/script-path-for-expressjs-in-node-modules) – Bryan Jun 25 '14 at 00:54
  • 1
    it would be great if this answer can touch on how one can get bootstrap-sass node_modules files available to gulp cleanly, i.e. im not really comfortable doing a one time copy programmed into a gulp task to copy the files into a src folder, so they can be sourced by gulp task on each recompile, and i dont think i should be getting used to copying files manually out of node_modules, so how can i avoid lamely using bower simply for the middle-man? manually copy them to src/ or is there a better gulp way to access node_modules, or what api calls ARE available to bootstrap-sass via gulp? – blamb Oct 12 '15 at 10:19
  • related post, seems everybody is running into this usage of node_modules from gulp now http://stackoverflow.com/questions/27464168/how-to-include-scripts-located-inside-the-node-modules-folder – blamb Oct 12 '15 at 10:27
  • I would like to see the last command expanded on, for example what if I wanted to only include certain node_modules files and not others. – Jackie Jan 01 '16 at 22:29