user2986042 user2986042 - 2 months ago 11
Node.js Question

How to acess path permission in Express nodejs?

I am completely new in express node.js . I have a folder structure like :

/Express
--server.js
--index.html
--home.html
/css/
/js/
/images
/fonts


In
index.html
i am accessing some
javascript (js folder)
,
images (images folder)
,
fonts (fonts folder)
. Also i am linking
home.html
from
index.html
page . I need to block accessing
home.html
directly also .

I wrote a
server.js
with
express-ws
like this :

var express = require('express');
var app = express();
var expressWs = require('express-ws')(app);
var path = require('path');

//accessing index.html
app.get('/', function(req, res){
res.sendFile(path.join(__dirname+'/index.html'));

});

//How can i acess all the files inside the JS , CSS , Image and Font folder here ???

//Also How can i link home.html from Index.html File and block home.html accessing publicly

app.ws('/', function(ws, req) {
ws.on('message', function(msg) {
console.log(msg);
});
console.log('socket', req.testing);
});

app.listen(8888);


Any suggestions how can i access all the files inside the JS , CSS , Image and Font folder from
index.html
with
server.js
? Also linking
home.html
from
index.html
with direct access block .

Answer

You should create a separate folder for static content like public or anything else and then use express.static() to serve static content. So here would be your updated directory structure

/Express 
   --server.js
   --index.html
   --home.html
   --/public/ (directory)
          --/css/ (directory)
          --/js/ (directory)
          --/images/ (directory)
          --/fonts/ (directory)

and your updated code would be

  var express = require('express');
  var app = express();
  var expressWs = require('express-ws')(app);
  var path = require('path');

  //for js, css, images and fonts
  app.use(express.static(path.join(__dirname, 'public')));

  //accessing index.html
  app.get('/', function(req, res){
    res.sendFile(path.join(__dirname, 'index.html'));

   });

   app.ws('/', function(ws, req) {
      ws.on('message', function(msg) {
       console.log(msg);
      });
      console.log('socket', req.testing);
    });

  app.listen(8888); 
Comments