Andres Darwin
Andres Darwin

Reputation: 51

Node js - public subfolder

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.

Upvotes: 0

Views: 2343

Answers (1)

Mu-Majid
Mu-Majid

Reputation: 845

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

Upvotes: 1

Related Questions