4

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.

3
  • What about hosting your js file(s) on a web server and specifying the complete URL of the js in the src attribute of the script tag Commented Oct 9, 2013 at 0:18
  • Check that link as well: stackoverflow.com/questions/11710995/… Commented Oct 9, 2013 at 0:20
  • sounds like express or one of the other REST toolkits. Commented Oct 9, 2013 at 0:31

1 Answer 1

2

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!

Sign up to request clarification or add additional context in comments.

Comments

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.