How to create a simple web server that can read a given file on a given disk via “readFile” function ?
Last Updated :
05 Aug, 2024
To create a web server we need to import the 'http' module using require() method and create a server using the createServer() method of the HTTP module.
Syntax:
const http = require('http')
const server = createServer(callback).listen(port,hostname);
Now in the callback in the createServer() method, we need to read the file from our local directory and serve it using our server. For this, we need to import the 'fs' module and use its readFile() method.
Syntax:
Importing 'fs' module:
const fs = require('fs')
fs.readFile():
fs.readFile( filename, encoding, callback_function)
Once we are done reading the file we need to render it on our server.
Project Setup: Create a file serving_files.js and set its directory as your current directory in your terminal.
Example 1: In this example, we are specifying in our code our filename serving_files.js so when we will run http://localhost/ in our browser, our file will be rendered.
serving_files.js
// Import http and fs
const fs=require('fs')
const http = require( 'http')
// Creating Server
http.createServer((req, res) =>{
// Reading file
fs.readFile(`serving_files.js`, function (err,filedata) {
if (err) {
// Handling error
res.writeHead(404);
res.end(JSON.stringify(err));
return;
}
// serving file to the server
res.writeHead(200);
res.end(filedata);
});
}).listen(80,'localhost');
Step to run the application: Run the following command in the terminal to start the server:
node serving_files.js
Output:
// Import http and fs
const fs=require('fs')
const http = require( 'http')
// Creating Server
http.createServer((req, res) =>{
// Reading file
fs.readFile(`serving_files.js`, function (err,filedata){
if (err) {
// Handling error
res.writeHead(404);
res.end(JSON.stringify(err));
return;
}
// serving file to the server
res.writeHead(200);
res.end(filedata);
});
}).listen(80,'localhost');
Example 2: In this example instead of specifying the file name in our code, we will do it by passing our filename in our request URL. So this way we can access any file from our server by specifying the file name in our request URL and we will not be limited to retrieving only one file.
So to open any file from our server we need to pass our request URL in the following manner:
http://hostname:port/file_name
In our example below our request URL would be http://localhost/serving_files.js
serving_files.js
// Import http and fs
const fs=require('fs')
const http = require( 'http')
// Creating Server
http.createServer((req, res) =>{
// Reading file
fs.readFile(__dirname + req.url, function (err,filedata) {
if (err) {
// Handling error
res.writeHead(404);
res.end(JSON.stringify(err));
return;
}
// serving file to the server
res.writeHead(200);
res.end(filedata);
});
}).listen(80,'localhost');
Step to run the application: Run the following command in the terminal to start the server:
node serving_files.js
Output:
// Import http and fs
const fs=require('fs')
const http = require( 'http')
// Creating Server
http.createServer((req, res) =>{
// Reading file
fs.readFile(__dirname + req.url, function (err,filedata) {
if (err) {
// Handling error
res.writeHead(404);
res.end(JSON.stringify(err));
return;
}
// serving file to the server
res.writeHead(200);
res.end(filedata);
});
}).listen(80,'localhost');
NOTE: In the above examples, we have used port 80 which is the default HTTP port. So even if we do not specify the port in our request URL then it is by default taken as 80.
In case you are using any other port number, specify it in your request URL. For example, if you are using port 8000, then your request URL would be
http://localhost:8000/serving_files.js
Similar Reads
How to Create a Simple Server in Node.js that Display Hello World ?
We will create a simple server in Node.js that returns Hello World using an express server. Node.js is a powerful JavaScript runtime built on Chrome's V8 engine, commonly used to build scalable network applications. One of the fundamental tasks when learning Node.js is creating a simple server that
2 min read
How to Create a Simple HTTP Server Listening at Port 3000 to Serve Video ?
Creating a simple HTTP server to serve a video file can be done using various programming languages and frameworks. For simplicity, we'll use Python, which has built-in modules that make this task straightforward. In this article, weâll guide you through setting up a basic HTTP server using Python t
3 min read
How to implement a function âgetScriptâ that fetches/executes a JavaScript file in browser ?
In this article, we will learn how to fetch a JavaScript file(.js) and load it in a web browser dynamically by using JavaScript with HTML. We need a web browser i.e., Chrome (recommended) or Electron Application. Sometimes we need to add a script in the document as per the requirement of the user in
2 min read
How To Create a Simple HTTP Server in Node?
NodeJS is a powerful runtime environment that allows developers to build scalable and high-performance applications, especially for I/O-bound operations. One of the most common uses of NodeJS is to create HTTP servers. What is HTTP?HTTP (Hypertext Transfer Protocol) is a protocol used for transferri
3 min read
How to load the contents of a text file into a JavaScript variable?
In this article, we will examine how to read the contents of any text file that exists on your computer into a variable using JavaScript. The following are a few basic pointers that everybody should brush through before looking at the code: Event listeners: These are predefined functions that exist
3 min read
How to add file uploads function to a webpage in HTML ?
Adding a file upload function to a webpage in HTML allows users to select and upload files from their device to a server. This is achieved using the <input type="file"> element within a form, enabling file selection and submission for processing or storage.Table of ContentUsing Single File Upl
2 min read
How to create input field that accept CSV file in HTML ?
CSV (Comma Separated Values) is a commonly used file format for storing tabular data. To allow users to upload CSV files to a web application, we can create an input field that accepts CSV files in HTML. There are different approaches to achieve this, ranging from the simple "accept" attribute in th
6 min read
Launch an HTTP Server with a Single Line of Python Code
Python, with its built-in capabilities, offers a simple and effective way to do this. With just a single line of code, you can launch an HTTP server to serve files from your local directory. This feature can be incredibly handy for developers, educators, and anyone needing a quick and easy way to sh
2 min read
Create a web server and run PHP script on it using Raspberry Pi
In this post, creating a web server and running PHP script on it using Raspberry Pi will be discussed. Web Servers are basically simple computer programs that dispense the web page when they are requested using the web client. The machines on which this program run are usually called as a server, wi
2 min read
How to Create a Simple Server Using ExpressJS?
The server plays an important role in the development of the web application. It helps in managing API requests and communication between the client and the backend. ExpressJS is the fast and famous framework of the Node.Js which is used for creating the server.In this article, we will create a simp
3 min read