Audience
The examples are very basic and focused for beginners.
Reading and Writing Files
The file system module provide a synchronous and asynchronous functions for reading and writing a file.
Example for reading a file using synchronous function fs.readFileSync.
const fs = require('fs'); const information = fs.readFileSync('files/file1.txt', 'utf8'); console.log(information);
Example for reading a file using asynchronous function fs.readFile.
const fs = require('fs'); const information = fs.readFile('files/file1.txt', 'utf8', (err, information) => { if (err) { console.log('Error occured while reading a file'); return; } console.log(information); });
Example for creating a file using synchronous function fs.writeFileSync.
const fs = require('fs'); const content = ` The file is created for demonstrating file I/O operation using Node.js Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. `; fs.writeFileSync('files/file-write-sync.txt', content, { encoding: 'utf8' }); console.log('file was created successfully');
Example for creating a file using asynchronous function fs.writeFile.
const fs = require('fs'); const content = ` The file is created for demonstrating file I/O operation using Node.js Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. `; fs.writeFile('files/file-write-async.txt', content, { encoding: 'utf8' }, (err) => { if (err) { console.log('file was not created!!'); return; } console.log('file was created successfully'); });Now when do you use synchronous and asynchronous function?
The synchronous function will block event loop until finishing their operations, which means the other functions are will be in event loop for a while (waiting for long time) when do you perform complex operations in synchronous mode. The synchronous operation will slow down the application performance and asynchronous functions are mostly advisable in Node.js.
Example for renaming a file.const fs = require('fs'); fs.rename('files/file1.txt', 'files/file1-rename.txt', (err) => { if (err) { console.log('file was not renamed successfully'); return; } console.log('file was renamed successfully'); });Example for deleting a file.
const fs = require('fs'); fs.unlink('files/file-write-async.txt', (err) => { if (err) { console.log('file was not deleted!!'); } console.log('file was deleted!!'); });Example for checking whether a file is exists.
const fs = require('fs'); if (fs.exists('files/file1.txt')) { console.log('File exists'); } else { console.log('File does not exists'); }
For some cases we may need to check whether a particular user has access for a directory or files. We can easily do it node and here is an example.
const fs = require('fs'); fs.access('files/file1.txt', fs.constants.R_OK | fs.constants.W_OK, (err) => { console.log(err ? 'no access' : 'can read and write'); });
fs.constants is an object which has constant values related to file operations.
fs.constants.R_OK // path can be read by calling process fs.constants.W_OK // path can be write by calling processReading a file using stream
The file system module provide a function called fs.ReadStream for reading a file using streams. We need to open a stream and listen for events for reading a data and this is desired method for reading big size files. Here is an example.
const fs = require('fs'); const stream = fs.ReadStream('files/file1.txt'); stream.on('data', (chunk) => { console.log(`Received ${chunk.length} bytes of data.`); }); stream.on('end', () => { console.log('No more data available for read'); }); stream.on('error', (err) => { console.log(`some error occured while reading a file ${err}`); });Writing a file using stream
The file system module provide a function called fs.WriteStream which is similar to read stream method. This allow us to open a stream and write a chunk of data. Here I am providing a simple example for copying a file using write stream method.
const fs = require('fs'); const source = fs.ReadStream('files/file1.txt'); const dest = fs.WriteStream('files/file2.txt'); source.on('data', (chunk) => { dest.write(chunk); }); source.on('end', () => { console.log('File was copied successfully'); dest.end(); });Reading a file using ReadLine module
The ReadLine module is helpful for reading a data from readble stream one line at a time. Here is an example will read a content from file (line by line) and print it in console.
const fs = require('fs'); const readline = require('readline'); const rl = readline.createInterface({ input: fs.createReadStream('files/file1.txt') }); rl.on('line', (line) => { console.log(line); }); rl.on('close', () => { console.log('done!!'); });
I have provided some simple examples of file operations using Node. Actually Node is having more capabilities for handling I/O and look at official documentation for more information.
Comments