Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Script path for ExpressJS in node_modules

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!

like image 704
Bryan Avatar asked Jun 24 '14 22:06

Bryan


People also ask

How do I find my node JS path?

We can get the path of the present script in node. js by using __dirname and __filename module scope variables. __dirname: It returns the directory name of the current module in which the current script is located.

What is the node_modules directory?

What exactly is the node_modules folder and what is it for? It just a directory created by npm and a way of tracking each packages you install locally via package.

What is Express () in node JS?

Express is a node js web application framework that provides broad features for building web and mobile applications. It is used to build a single page, multipage, and hybrid web application. It's a layer built on the top of the Node js that helps manage servers and routes.


1 Answers

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')));
like image 90
a_arias Avatar answered Oct 06 '22 20:10

a_arias