Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js quick file server (static files over HTTP)

Is there Node.js ready-to-use tool (installed with npm), that would help me expose folder content as file server over HTTP.

Example, if I have

D:\Folder\file.zip D:\Folder\file2.html D:\Folder\folder\file-in-folder.jpg 

Then starting in D:\Folder\ node node-file-server.js I could access file via

http://hostname/file.zip http://hostname/file2.html http://hostname/folder/file-in-folder.jpg 

Why is my node static file server dropping requests? reference some mystical

standard node.js static file server

If there's no such tool, what framework should I use?

Related: Basic static file server in NodeJS

like image 353
Paul Verest Avatar asked May 02 '13 08:05

Paul Verest


People also ask

How do I serve a static file in node JS?

In your node application, you can use node-static module to serve static resources. The node-static module is an HTTP static-file server module with built-in caching. First of all, install node-static module using NPM as below. After installing node-static module, you can create static file server in Node.

How do you serve a static file?

To serve static files for Go 1.12+ in the standard environment, you define the handlers in your app. yaml file using either the static_dir or static_files elements. The content in the static files or static directories are unaffected by the scaling settings in your app.

What is HTTP createServer in node JS?

The http. createServer() method turns your computer into an HTTP server. The http. createServer() method creates an HTTP Server object. The HTTP Server object can listen to ports on your computer and execute a function, a requestListener, each time a request is made.


2 Answers

If you do not want to use ready tool, you can use the code below, as demonstrated by me at https://developer.mozilla.org/en-US/docs/Node_server_without_framework:

var http = require('http'); var fs = require('fs'); var path = require('path');  http.createServer(function (request, response) {     console.log('request starting...');      var filePath = '.' + request.url;     if (filePath == './')         filePath = './index.html';      var extname = path.extname(filePath);     var contentType = 'text/html';     switch (extname) {         case '.js':             contentType = 'text/javascript';             break;         case '.css':             contentType = 'text/css';             break;         case '.json':             contentType = 'application/json';             break;         case '.png':             contentType = 'image/png';             break;               case '.jpg':             contentType = 'image/jpg';             break;         case '.wav':             contentType = 'audio/wav';             break;     }      fs.readFile(filePath, function(error, content) {         if (error) {             if(error.code == 'ENOENT'){                 fs.readFile('./404.html', function(error, content) {                     response.writeHead(200, { 'Content-Type': contentType });                     response.end(content, 'utf-8');                 });             }             else {                 response.writeHead(500);                 response.end('Sorry, check with the site admin for error: '+error.code+' ..\n');                 response.end();              }         }         else {             response.writeHead(200, { 'Content-Type': contentType });             response.end(content, 'utf-8');         }     });  }).listen(8125); console.log('Server running at http://127.0.0.1:8125/'); 

UPDATE If you need to access your server from external demand/file, you need to overcome the CORS, in your node.js file by writing the below, as I mentioned in a previous answer here

// Website you wish to allow to connect response.setHeader('Access-Control-Allow-Origin', '*');  // Request methods you wish to allow response.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');  // Request headers you wish to allow response.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');  // Set to true if you need the website to include cookies in the requests sent // to the API (e.g. in case you use sessions) response.setHeader('Access-Control-Allow-Credentials', true); 

UPDATE

As Adrian mentioned, in the comments, he wrote an ES6 code with full explanation here, I just re-posting his code below, in case the code gone from the original site for any reason:

const http = require('http'); const url = require('url'); const fs = require('fs'); const path = require('path'); const port = process.argv[2] || 9000;  http.createServer(function (req, res) {   console.log(`${req.method} ${req.url}`);    // parse URL   const parsedUrl = url.parse(req.url);   // extract URL path   let pathname = `.${parsedUrl.pathname}`;   // based on the URL path, extract the file extension. e.g. .js, .doc, ...   const ext = path.parse(pathname).ext;   // maps file extension to MIME typere   const map = {     '.ico': 'image/x-icon',     '.html': 'text/html',     '.js': 'text/javascript',     '.json': 'application/json',     '.css': 'text/css',     '.png': 'image/png',     '.jpg': 'image/jpeg',     '.wav': 'audio/wav',     '.mp3': 'audio/mpeg',     '.svg': 'image/svg+xml',     '.pdf': 'application/pdf',     '.doc': 'application/msword'   };    fs.exists(pathname, function (exist) {     if(!exist) {       // if the file is not found, return 404       res.statusCode = 404;       res.end(`File ${pathname} not found!`);       return;     }      // if is a directory search for index file matching the extension     if (fs.statSync(pathname).isDirectory()) pathname += '/index' + ext;      // read file from file system     fs.readFile(pathname, function(err, data){       if(err){         res.statusCode = 500;         res.end(`Error getting the file: ${err}.`);       } else {         // if the file is found, set Content-type and send data         res.setHeader('Content-type', map[ext] || 'text/plain' );         res.end(data);       }     });   });   }).listen(parseInt(port));  console.log(`Server listening on port ${port}`); 
like image 35
Hasan A Yousef Avatar answered Sep 23 '22 06:09

Hasan A Yousef


A good "ready-to-use tool" option could be http-server:

npm install http-server -g 

To use it:

cd D:\Folder http-server 

Or, like this:

http-server D:\Folder 

Check it out: https://github.com/nodeapps/http-server

like image 107
Matt Self Avatar answered Sep 25 '22 06:09

Matt Self