Creating Server in nodejs & File System In Node js
Creating a server in Node.js is straightforward, thanks to the built-in http
module. Below is a step-by-step guide to setting up a simple HTTP server.
- Read files
- Create files
- Update files
- Delete files
- Rename files
Read Files
The fs.readFile()
method is used to read files on your computer. Assume we have the following HTML file (located in the same folder as Node.js):
Index.html file
is a method call used in Node.js to set the status code and response headers of an HTTP response. Here's a breakdown of what it does:
200
: This is the HTTP status code for "OK," indicating that the request has been
successfully processed.
{'Content-Type': 'text/html'}
: This is an object specifying the headers
for the HTTP response. In this case:
Content-Type
is set to text/html
, which informs the client
(e.g., a browser) that the response content will be HTML.
Read Files, with Synchronous note pad File Read.
The fs.readFile()
method is used to read files on your computer. Synchronous File Read ,This blocks the execution of the code until the file is read:
Create Files
The File System module has methods for creating new files:
fs.appendFile()
fs.open()
fs.writeFile()
fs.appendFile()
method appends specified content to a file. If the file does not exist, the file will be created:
fs.open()
method takes a "flag" as the second argument, if the flag is "w" for "writing", the specified file is opened for writing. If the file does not exist, an empty file is created:fs.writeFile()
method replaces the specified file and content if it exists. If the file does not exist, a new file, containing the specified content, will be created:Delete Files
To delete a file with the File System module, use the fs.unlink()
method. The fs.unlink()
method deletes the specified file:
Rename Files
To rename a file with the File System module, use the fs.rename()
method. The fs.rename()
method renames the specified file: