Saturday 16 February 2019

Express Module: Send static files


'express.static' (It ships as part of express) module used to serve static files presented in a directory.

Below program serves the static files that are located in ./resources directory.

Project structure looks like below




a. Create resources directory.

b. Create files greet.txt, hello.txt under resources directory.
greet.txt
Greeting


hello.txt
Hello World

c. Create a directory ‘css’ under resources directory.

d. Create tiles.css under ‘css’ directory.

tiles.css
p.one {
    border-style: solid;
    border-width: 5px;
}

p.two {
    border-style: solid;
    border-width: medium;
}

p.three {
    border-style: dotted;
    border-width: 2px;
}

p.four {
    border-style: dotted;
    border-width: thick;
}

e. Create fileServer.js, make sure fileserver.js, resources directories are under one parent directory.

fileServer.js
var express = require("express");
var path = require("path");
var app = express();

const port = 8080;

//static files path is currentDirectory + PathSeparator + resources
var resourcesPath = path.resolve(__dirname, "resources"); 
app.use(express.static(resourcesPath));

app.use(function(request, response) {
 response.writeHead(200, { "Content-Type": "text/plain" });
 response.end("Static file requested by user is not present");
});

// Start the express application on port 8080 and print server start message to console.
app.listen(port, () => console.log(`Application started listening on port ${port}!`));

Open terminal (or) command promt and execute below statement.

node fileServer.js

You can see below message in the console.
Application started listening on port 8080!

Open browser and hit the below url to get the content of hello.txt.


Hit the url 'http://localhost:8080/css/tiles.css' to get the content of tiles.css file.




Previous                                                 Next                                                 Home

No comments:

Post a Comment