How to acess path permission in Express nodejs? - html

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 .

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);

add following after requiring path
// serve index.css at localhost:3000/index.css
app.use(express.static('css')); // looks in current directory for css folder
// serve index.js at localhost:3000/static/index.js
app.use('/static', express.static('js')); // looks in current directory for js folder and appends /static to URL
app.use(express.static('fonts'));
Reference on serving static files from express

Related

How to check if an HTML file is in a given directory, and then open that file with the referenced CSS and JS files within same directory

For my homework problem, I need to check if a file exists in a certain
directory "public", and then if it does, open it up through the
localhost in a browser. I wanted to use a function to check if the file
exists in directory, and then if true, send the file path to another function that'll open the file. This is all on my server.js file, and the HTML file I want to open along with the CSS and JS for the HTML file are all in my public directory.
This is using node.js. I need to run node server.js in the console, and then go to my localhost in a browser and see the displayed webpage with style and functionality. I've tried using fs.access and fs.existsSync. We are not allowed to use express on this assignment.
var http = require('http');
var fs = require('fs');
http.createServer(function(req, res) {
var filepath = 'public' + req.url;
if (req.url == '/index.html' || req.url == '/') {
fs.access(filepath);
}
}).listen(3000);
console.log("Server running on Port 3000...");
fs.access(filepath, (access) =>{
if (access) {
res.statusCode = 200;
sendFile(filepath, res);
}
else {
res.statusCode = 404;
sendFile('public/404.html', res);
}
});
function sendFile(path, res) {
fs.readFile(path, "utf8", function(data){
res.end(data);
});
}
I'm getting an error that says filepath is not defined (when I use it in the parameters when I call fs.access.
fs requires paths with a leading slash to work, so instead of var filepath = 'public' + req.url;, try
var filepath = '/public' + req.url;

nodeJs display on web browser

Just want to display my node.js result on web browser..
is it possible?...
here's my code:
const testFolder = 'texts/';
const fs = require('fs');
fs.readdirSync(testFolder).forEach(file => {
console.log(file);
})
when I try to run that code on cmd it works. The code gets all the .txt file on a specific directory.
here's the result:
then when i tried to load it on my browser the result goes like this
Im also planing to add all the result filename to database mysql once the node.js code fixed.. is that also possible?..
thank you.. this is my first time to create a node.js
Use the express router to accept GET request from your browser :
const express = require('express');
const fs = require('fs');
const app = express();
const testFolder = 'texts/';
// To set your public directory and use relative url
app.use(express.static(__dirname + 'your_public_dir'));
// When you access to localhost:8080, it will send GET '/' request
app.get('/', function(req,res) {
fs.readdirSync(testFolder).forEach(file => {
console.log(file);
});
});
Nicolas is right, express can achieve this. Just remember to install it using NPM, this can be done by executing following command under the directory where package.json is:
npm install --save express
however, you would also need to write into response of the server so it shows on website. So for example, using Express:
app.get('/', function(req,res) {
res.write("whatever you want to display");
res.end()
});

Compile EJS templates to HTML in separate folder

I need to export my ejs templates to html files in a separate "dist" folder at the root of my project. I do have gulp-ejs installed and have the following setup in my gulpfile.js, but it is not creating the folder and compiling the html files to it:
var gulp = require('gulp'),
sass = require('gulp-sass'),
cssbeautify = require('gulp-cssbeautify'),
ejs = require('gulp-ejs');
gulp.task('styles', function(){
gulp.src('sass/**/*.scss')
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('./css/')
);
});
gulp.task('css', function(){
return gulp.src('./styles/*.css')
.pipe(cssbeautify({
indent: ' ',
openbrace: 'end-of-line',
autosemicolon: true
}))
.pipe(gulp.dest('./styles/'));
});
gulp.task('ejs', function(){
return gulp.src('./views/pages/*.ejs')<----SHOULD GRAB ALL EJS PAGES
.pipe(ejs({}, {ext:'.html'})) <-----ADD EXTENSION OF .HTML
.pipe(gulp.dest('./dist')) <-----AND EXPORT THEM TO THE DIST FOLDER
});
//Watch
gulp.task('default', function(){
gulp.watch('sass/**/*.scss',['styles','css','ejs']);
});
Also, my directory structure is as follows:
-css
-node_modules
-routes
-sass
-views
|-pages
|-about.ejs
|-index.ejs
|-partials
|-head.ejs
|-nav.ejs
-gulpfile.js
-package.json
-server.js
I think you should add another {} to ejs parameters.
ejs(data,option,settings)
gulp.task('ejs', function(){
return gulp.src('./views/pages/*.ejs')<----SHOULD GRAB ALL EJS PAGES
.pipe(ejs({},{}, {ext:'.html'})) <-----ADD EXTENSION OF .HTML
.pipe(gulp.dest('./dist')) <-----AND EXPORT THEM TO THE DIST FOLDER
});
This is how I do it and it works for me. (using gulp-ejs 3.0.0)
https://github.com/mde/ejs & https://github.com/rogeriopvl/gulp-ejs

Displaying local images in static html served by NodeJS

I have a NodeJS app that renders index.html, but I can't get index.html to find the images in the folder it's located in.
Here are the contents of index.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get ('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
http.listen(80, function(){
console.log('listening on *:80');
});
It serves index.html successfully but all images I supply it are broken links.
The following html does not work
<img src="img/myimage.png">
and my file structure is
myApp - folder
index.js
index.html
img - folder
myimage.png
I've tried several variations such as
<img src="/img/myimage.png">
<img src="./img/myimage.png">
I've also tried placing the image directly in the app folder with index.html and trying
<img src="myimage.png">
But the link to the image is still broken.
const express = require("express");
const app = express();
If you have the images in a folder named "Images" and you want to point to the image in the folder as "img/myimage.png", then use this:
app.use('/img', express.static(__dirname + '/Images'));
This way you can also keep your actual images folder name private.
I was able to resolve the issue by changing
var app = require('express')();
into
var express = require('express');
var app = express();
I then added
app.use(express.static(__dirname + '/img/'));
In the declaration of static file you will use in the express app, you have to put your files (images, songs, file) into public folder. Then, your express and ejs will show your file from the public folder as a root of that file.
var express = require("express");
var app = express();
app.use(express.static('public'));
app.set("view engine", "ejs");
app.get("/", function(req, res){
res.render("main");
});
app.listen(3000, function(req, res){
console.log("Auth server started!");
});
EJS folder is right here.
<h1>Secret Page!</h1>
<img src="anna.jpg"/>
<img src="https://i.imgur.com/NcXbX08.jpg" alt="">
After all, reload your nodejs app.
Do you mean broken links in the browser ? so the browser can not open the links rendered in index.html ?
The browser will probably need full paths to the images .. it doesn't seem that your node server is sending the full paths in the index.html file it passes to the browser.. have a look on that ..

How to include subdirectories in gulp task

I am just getting started with Gulp.
I have this:
var path = require('path');
var appRoot = 'src/';
var outputRoot = 'dist/';
module.exports = {
root: appRoot,
source: appRoot + '**/*.js',
html: appRoot + '**/*.html',
style: 'styles/**/*.css',
output: outputRoot,
doc:'./doc',
e2eSpecsSrc: 'test/e2e/src/*.js',
e2eSpecsDist: 'test/e2e/dist/'
};
This pathing is used to convert the source files from ES6 to ES5, and then drop in them in the dist directory. This all works fine.
However, it only takes the files from the src directory, not subfolders. How do I include the subfolders such as src\dir1 and src\dir2?
src/**/*.js should take care of all js files in all subfolders.