nodejs static file server code example

Example 1: node express server static files

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

//app.use(express.static(__dirname)); // Current directory is root
app.use(express.static(path.join(__dirname, 'public'))); //  "public" off of current is root

app.listen(80);
console.log('Listening on port 80');

Example 2: access to static file nodejs

app.use(express.static(__dirname + '/public'));
<link rel="stylesheet" type="text/css" href="css/style.css" />

Example 3: how to use static file node js

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

Example 4: how to use static file node js

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

Example 5: how can node js file be serve

var fs = require('fs'),
    http = require('http');

http.createServer(function (req, res) {
  fs.readFile(__dirname + req.url, function (err,data) {
    if (err) {
      res.writeHead(404);
      res.end(JSON.stringify(err));
      return;
    }
    res.writeHead(200);
    res.end(data);
  });
}).listen(8080);

Example 6: app.use public

express.static(root, [options])