2

I am learning to use node.js.

The site looks fine when run from file:///C:/.../myfolder/index.html I have my jquery and bootstrap files in the directories myfolder/css/ and myfolder/js.

but when I run node index.js and go to localhost:3000, these css and js files cannot be found.

This is what is in my index.html file:

 <link href="/css/bootstrap.min.css" rel="stylesheet">
 <script src="/js/bootstrap.min.js"></script>
 <script src="/js/jquery.js"></script>
 <script src="/socket.io/socket.io.js"></script>

Is there some folder in nodejs that I'm supposed to store these files? Or do I have to put some code in index.js that imports all the css and js files?

flyinglizard
  • 33
  • 1
  • 4

4 Answers4

0

Your localhost begins in a specific directory on you machine. If you use Xampp, you must put all your server files in C:\xampp\htdocs\ in order to acces these via your localhost URL. Some other servers use a folder called 'www'.

Find your server root path en put your files there. Or create a symlink from your server root to your files.

sampie777
  • 134
  • 6
0

Did you require the path module?

var path = require('path');

It's best to create a public directory to store your files in.

public/index.html
public/css/style.css
public/js/scripts.js
Tim
  • 1,680
  • 2
  • 15
  • 21
0

You can simply follow the quick start instructions for Express.js here:

https://www.npmjs.org/package/express

Then browse to http://localhost:3000 to test

You can use the Atom text editor or Brackets and place your files under the public folder and reference them.

http://atom.io
http://brackets.io

By default Express uses a template engine called Jade. You can look here to work with that:

http://jade-lang.com/

Using HTML in Express instead of Jade

Node.js + Express without using Jade

Good luck!

Community
  • 1
  • 1
Timmerz
  • 6,090
  • 5
  • 36
  • 49
  • Closest answer! After trawling through express documentation, I found that by adding the line app.use(express.static(__dirname + '/public')); where my css and js folders are in public folder, it works. – flyinglizard Nov 09 '14 at 02:56
0

The reason that you couldn't get access to localhost:3000/folder/file is that localhost:port is just a virtual port. There is no such directory called localhost:3000/css/ or localhost:3000/js.

To fix this, you need to use express module to configure the root directory from which to serve static assets.

Basically, you need to add the following code:

var express=require('express');
var app=express();
var path=require('path');    
app.use(express.static(path.join(__dirname,'public')));

and your static files directory will be currentWorkingDirectory/public/, which contains all of your assets.

In your code, to link any source file,

href='/fileName.extention'

Here is the documentation link express-static-files

Praveen
  • 1,791
  • 3
  • 20
  • 33
Janice Zhong
  • 836
  • 7
  • 16