Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make the node.js server also send js files?

I have a node.js file server running which (when visited) returns a html content. Also in the same directory of the node.js file, there is a javascript file called test.js. Also in the html content being returned, I need to load that javascript file. However in the html content, being returned, which comes out to be called index.html, the script looks like

<script type="text/javascript" src="test.js"></script>

But the server isn't sending the test.js file, its only sending the index.html file, and the script link is loading it relatively from the same directory.

Now I don't want to give the url to the test.js file. I want the node.js file to also send the test.js file, so that it ends up in the same directory as index.html. And then index.html can load it from the same directory.

Is there a way I can specify in the node.js with code to also send the test.js file?

Thanks.

like image 285
omega Avatar asked Mar 06 '26 12:03

omega


1 Answers

Are you familiar with Express, as dandavis mentioned? Express allows you to set a directory for your static files. See my standard config below:

app
  .use('view engine', jade)
  .use(express.compress())
  .use(express.limit('10mb'))
  .use(express.bodyParser())
  .use(app.router)
  .use(stylus.middleware({
     src: __dirname + '/www',
     compile: function(str, path) {
          return stylus(str)
              .set('filename', path)
              .set('compress', false)
              .set('warn', true);
        }
    }))
  .use(express.static(__dirname + '/www'))
  .use(express.logger());

The important part here is second from the bottom. Essentially, Express now knows to look for any assets you specify in your HTML within that static directory. For me, I create a folder titled WWW within my server folder, then add to it my JS, CSS, and images. For example, say I create the "stylus" folder within my WWW folder, and add to it store.css. My link to that CSS asset would be the following in my Jade template:

link(rel="stylesheet", type="text/css", href="stylus/store.css")

Express knows to look for that asset relative to the __dirname + '/www' path, and thus locates the "stylus" folder and the CSS assets it contains. Hope this helps, and that I haven't ventured away from your intent!

like image 96
Ryan Miller Avatar answered Mar 09 '26 00:03

Ryan Miller



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!