简体   繁体   中英

Node.js - How to link to local file?

I have a basic script source link:

// index.html
<script src="/js/jquery.js"></script>

Which doesn't work, despite the file existing. I tried to link to it in the Node.js server but it threw an error that express wasn't defined, yet it is.

//server.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var clientlist = [];

app.get('/', function(req, res) {
    res.sendfile('index.html');
    app.use(express().static('/js/jquery.js'));
});

Here is my solution.

Note:

You may want to replace '/var/www/nodeserver', with the directory, you are working in!

First of all, don't use res.sendfile() , it is deprecated, use res.sendFile() instead.
Or just serve a complete directory:

Setting all up

index.js

This could be your 'index.js' in '/var/www/nodeserver':

// Setup basic express server
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);

// Change 3000 to whatever port, you want to access the site with"http://127.0.0.1:3000"
var port = process.env.PORT || 3000;

server.listen(port, function() {
    console.log("Server listening at port "+port);
});

// Routing
var dir = __dirname+'/public'; // Path of the index.js but one dir further (public)
app.use(express.static(dir)); // serve all files in '/var/www/nodeserver/public/'

package.json

And you would need to have a 'package.json', containing this:

{
    "name": "nameofyourapplication",
    "version": "versionofyourapplication",
    "dependencies": {
        "express": "^4.10.2",
        "socket.io": "^1.3.7"
    }
}

Installation

Then install the dependencies defined in the 'package.json', with this command: npm install , while in the directory '/var/www/nodeserver/'.
This will install all the dependencies, locally, so it will create a folder named 'node_modules', in '/var/www/nodeserver'.

Using it

Next you just need to put all the files you want to serve, into the 'public' folder in '/var/www/nodeserver' and run the 'index.js' with node index.js .

The Filetree

Your filetree should then look something like this:

  • nodeserver
    • node_modules
      • express
      • socket.io
    • public
      • js
        • jquery.js
    • index.js
    • package.json

That should do it!

Your requires are wrong , and hence express is not defined

Chamnge your first line var app = require('express');

var express = require('express');
var app = express();

Before your file name put __dirname,'index.html'. New code will be res.sendfile(__dirname + 'index.html');

And also your first line is wrong it should be var express = require('express');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM