Question

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?

Was it helpful?

Solution

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>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top