TransWikia.com

Node js - public subfolder

Stack Overflow Asked by Andres Darwin on December 20, 2021

I have a Node.js server which was working fine, but now can’t serve a file in a public sub folder. My code is:

.use(express.static(path.join(__dirname, 'public'))

I can get files in public folder but not in public/Movimientos.

One Answer

The following example serves static resources from the public folder under the root folder of your application.

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

//setting middleware
app.use(express.static(__dirname + 'public')); //Serves resources from public folder


var server = app.listen(5000);

In the above example, app.use() method mounts the middleware express.static for every request. The express.static middleware is responsible for serving the static assets of an Express.js application. The express.static() method specifies the folder from which to serve all static resources.

Now, run the above code using node server.js command and point your browser to http://localhost:5000/myImage.jpg and it will display myImage.jpg from the public folder (public folder should have myImage.jpg).

If you have different folders for different types of resources then you can set express.static middleware as shown below.

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

app.use(express.static('public'));

//Serves all the request which includes /images in the url from Images folder
app.use('/images', express.static(__dirname + '/Images'));

var server = app.listen(5000);

In the above example, app.use() method mounts the express.static middleware for every request that starts with "/images". It will serve images from images folder for every HTTP requests that starts with "/images". For example, HTTP request http://localhost:5000/images/myImage.png will get myImage.png as a response. All other resources will be served from public folder.

Now, run the above code using node server.js and point your browser to http://localhost:5000/images/myImage.jpg and it will display myImage.jpg from the images folder, whereas http://localhost:5000/myJSFile.js request will be served from public folder. (images folder must include myImage.png and public folder must include myJSFile.js)

You can also create a virtual path in case you don't want to show actual folder name in the url.

app.use('/resources',express.static(__dirname + '/images'));

Answered by Mu-Majid on December 20, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP