1

I have inlcuded a static Html in node.js. In that html I want to import a js file.

I tried with:

<script src="some.js"></script>

But it actually does not get included.

How to make it work, please suggest?

4
  • are you using express.js? Commented May 2, 2014 at 9:00
  • no i am not using express.js ? Commented May 2, 2014 at 9:14
  • I recommend using express, and then you can make a folder your static directory and you can serve your javascript file easily Commented May 2, 2014 at 9:17
  • can you guide me how to do this using express ? Commented May 2, 2014 at 10:53

1 Answer 1

2

First Install express by this command:

npm install express

then create a folder named public in the directory where your server.js resides. Your directory structure should be like this:

server.js
public //public is a folder
  index.html
  javascript //javascript is also a folder
    some.js  //this is your javascript folder inside public/javascript folder

and do this in your server.js:

var express = require('express')
, http = require('http')
, var fs = require('fs');
, path = require('path');
var app = express();
app.configure(function () {
  app.set('port', process.env.PORT || 8000);
  app.use(express.static(path.join(__dirname, 'public')));
});
var server = http.createServer(app);
server.listen(app.get('port'), function () {
  console.log("Express server listening on port " + app.get('port'));
});

//create a route
app.get('/', function (req, res) {
  res.sendfile('public/test.html');
});

And in your html include it like this:

<script type="text/javascript" src="javascript/some.js"></script>
Sign up to request clarification or add additional context in comments.

1 Comment

app.configure() is no longer part of Express 4 (as per this S.O. answer

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.