- Home
-
HTML
HTML Introduction HTML Tags HTML Elements HTML Attributes HTML Heading HTML Paragraph HTML Formatting HTML Quotations HTML Comments HTML Styles HTML Color HTML CSS HTML Images HTML Favicon HTML Links HTML DIV HTML Tables HTML Table Size HTML Table Head Table Padding & Spacing Table colspan rowspsn HTML Table Styling HTML Colgroup HTML List HTML Block & Inline HTML Classes HTML Id HTML Iframes HTML Head HTML Layout HTML Semantic Elements HTML Style Guide HTML Forms HTML Form Attribute HTML Form Element HTML input type HTML Computer code HTML Entity HTML Symbol HTML Emojis HTML Charset HTML Input Form Attribute HTML URL Encoding
-
CSS
CSS Introduction CSS Syntax CSS Selector How To Add CSS CSS Comments CSS Colors CSS Background color CSS background-image CSS Borders CSS Margins CSS Height, Width and Max-width CSS Box Model CSS Outline CSS Text CSS Fonts CSS Icon CSS Links CSS Tables CSS Display CSS Maximum Width CSS Position z-index Property
- JavaScript
-
JQuery
What is jQuery? Benefits of using jQuery Include jQuery Selectors. Methods. The $ symbol and shorthand. Selecting elements Getting and setting content Adding and removing elements Modifying CSS and classes Binding and Unbinding events Common events: click, hover, focus, blur, etc Event delegation Using .on() for dynamic content Showing and hiding elements Fading elements in and out Sliding elements up and down .animate() Understanding AJAX .ajax() .load(), .get(), .post() Handling responses and errors. Parent Chlid Siblings Filtering Elements Using find Selecting form elements Getting form values Setting form values Form validation Handling form submissions jQuery plugins Sliders plugins $.each() $.trim() $.extend() Data attributes Debugging jQuery code
-
Bootstrap 4
What is Bootstrap Benefits of using Setting up Container Row and Column Grid Classes Breakpoints Offsetting Columns Column Ordering Basic Typography Text Alignment Text colors Backgrounds Display Font Size Utilities Buttons Navs and Navbar Forms Cards Alerts Badges Progress Bars Margin Padding Sizing Flexbox Dropdowns Modals Tooltips Popovers Collapse Carousel Images Tables Jumbotron Media Object
- Git
-
PHP
PHP Introduction PHP Installation PHP Syntax PHP Comments PHP Variable PHP Echo PHP Data Types PHP Strings PHP Constant PHP Maths PHP Number PHP Operators PHP if else & if else if PHP Switch PHP Loops PHP Functions PHP Array PHP OOps PHP Class & Object PHP Constructor PHP Destructor PHP Access Modfiers PHP Inheritance PHP Final Keyword PHP Class Constant PHP Abstract Class PHP Superglobals PHP Regular Expression PHP Interfaces PHP Static Method PHP Static Properties PHP Namespace PHP Iterable PHP Form Introduction PHP Form Validation PHP Complete Form PHP Date and Time PHP Include Files PHP - Files & I/O File Upload PHP Cookies PHP SESSION PHP Filters PHP Callback Functions PHP JSON PHP AND Exceptions PHP Connect database
-
MY SQL
SQL Introduction Syntax Select statement Select Distinct WHERE Clause Order By SQL AND Operator SQL OR Operator SQL NOT Operator SQL LIKE SQL IN SQL BETWEEN SQL INSERT INTO SQL NULL Values SQL UPDATE SQL DELETE SQL TOP, LIMIT, FETCH FIRST or ROWNUM Clause SQL MIN() and MAX() Functions SQL COUNT() Function SQL SUM() SQL AVG() SQL Aliases SQL JOIN SQL INNER JOIN SQL LEFT JOIN SQL RIGHT JOIN SQL FULL OUTER JOIN SQL Self Join SQL UNION SQL GROUP BY SQL HAVING SQL EXISTS SQL ANY and ALL SQL SELECT INTO SQL INSERT INTO SELECT SQL CASE SQL NULL Functions SQL Stored Procedures SQL Comments SQL Operators SQL CREATE DATABASE SQL DROP DATABASE SQL BACKUP DATABASE SQL CREATE TABLE SQL DROP TABLE SQL ALTER TABLE SQL Constraints SQL NOT NULL SQL UNIQUE Constraint SQL PRIMARY KEY SQL FOREIGN KEY SQL CHECK Constraint SQL CREATE INDEX SQL AUTO INCREMENT SQL Dates SQL Views SQL Injection SQL Hosting SQL Data Types
Modules fs in node js
Understanding the fs
Module in Node.js
The fs
module in Node.js is a built-in module that provides an API for interacting with the file system. It allows you to perform various operations like reading, writing, updating, and deleting files and directories.
Key Features of the fs
Module
- Reading Files: Read the content of a file.
- Writing Files: Write data to a file.
- Appending Files: Append data to an existing file.
- Deleting Files: Remove files from the system.
- Directory Operations: Create, read, and delete directories.
Installation with npm
In earlier versions of Node.js, you would typically install modules via npm, including built-in ones like fs
. However, fs
is a core module, so you don't need to install it separately. The command npm install fs --save
is outdated for fs
as it’s already included in Node.js by default.
Example 1: Reading a File
Let's start with reading a file using the fs
module.
Code:
const fs = require('fs');
// Reading a file asynchronously
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) {
console.error('Error reading the file:', err);
return;
}
console.log('File content:', data);
});
Explanation:
fs.readFile
reads the content of the file asynchronously.'example.txt'
is the file you want to read.'utf8'
specifies the encoding.- The callback function receives an error object
err
(if any) and the file contentdata
.
Output:
If the file example.txt
contains:
Hello, Node.js!
The output in the console will be:
File content: Hello, Node.js!
Example 2: Writing to a File
Next, let’s write some data to a file.
Code:
const fs = require('fs');
// Writing to a file asynchronously
fs.writeFile('output.txt', 'Hello, Node.js!', 'utf8', (err) => {
if (err) {
console.error('Error writing to the file:', err);
return;
}
console.log('File has been written successfully!');
});
Explanation:
fs.writeFile
writes data to a file asynchronously.'output.txt'
is the file where the content will be written.'Hello, Node.js!'
is the content to be written.'utf8'
specifies the encoding.
Output:
A file named output.txt
will be created with the content:
Hello, Node.js!
Console output:
File has been written successfully!
Example 3: Appending to a File
Appending data to an existing file is also straightforward.
Code:
const fs = require('fs');
// Appending to a file asynchronously
fs.appendFile('output.txt', '\nThis is additional content.', 'utf8', (err) => {
if (err) {
console.error('Error appending to the file:', err);
return;
}
console.log('Content has been appended successfully!');
});
Explanation:
fs.appendFile
adds data to an existing file.- The content
\nThis is additional content.
will be added at the end of the fileoutput.txt
.
Output:
If output.txt
initially contained:
Hello, Node.js!
After running the code, it will contain:
Hello, Node.js!
This is additional content.
Console output:
Content has been appended successfully!
Example 4: Deleting a File
Deleting a file is just as easy.
Code:
const fs = require('fs');
// Deleting a file asynchronously
fs.unlink('output.txt', (err) => {
if (err) {
console.error('Error deleting the file:', err);
return;
}
console.log('File has been deleted successfully!');
});
Explanation:
fs.unlink
is used to delete a file.'output.txt'
is the file to be deleted.
Output:
If output.txt
exists, it will be deleted, and the console will show:
File has been deleted successfully!
Example 5: Working with Directories
You can also create and remove directories using the fs
module.
Creating a Directory:
const fs = require('fs');
// Creating a new directory
fs.mkdir('new_directory', { recursive: true }, (err) => {
if (err) {
console.error('Error creating directory:', err);
return;
}
console.log('Directory created successfully!');
});
Deleting a Directory:
const fs = require('fs');
// Deleting a directory
fs.rmdir('new_directory', { recursive: true }, (err) => {
if (err) {
console.error('Error deleting directory:', err);
return;
}
console.log('Directory deleted successfully!');
});
Conclusion
The fs
module is powerful and essential for file system operations in Node.js. With it, you can easily manage files and directories within your application. Remember, since fs
is a core module, there’s no need to install it separately using npm.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2024 © All rights reserved.