Skip to main content

Posts

Showing posts from September, 2018

Node.JS - File operation examples

File operations are very common requirements and I thought of providing some simple examples in Node.js. The Node.js provide a module called "fs" which is having all necessary functions for performing file operations. Let's start with very simple examples. 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; } ...