NodeJs: Read Text File

Last weekend i tried studying NodeJs. I was surprised how simple it was, and it easier to use than i expected. Based on the documentation, it seems to be powerful, so i might use it for some maintenance script required in my future projects.

I was able to create a simple script, a text file reader. Below is the two version of the code, asynchronous and synchronous version. It uses the file system (fs) API of NodeJs.

Asynchronous version


const fs = require('fs');

root_path = 'files';
encoding = 'utf8';

fs.readdir(root_path, encoding, (err, files) => {
	if(files.length > 0)
	{
		for(file in files)
		{
			file_to_read = root_path + '/' + files[file];
			fs.readFile(file_to_read, encoding, (err, content) => {
				rows = content.split('\n');
				if(rows.length > 0)
				{
					for(row in rows)
					{
						console.log(`--- ${rows[row]}`);
					}
				}
				else
				{
					console.log('no row was found');
				}
			});
		}		
	}
	else
	{
		console.log('--- no files found');
	}
});

Synchronous version


const fs = require('fs');

root_path = 'files';
files = fs.readdirSync(root_path);

if(files.length > 0)
{
	for(file in files)
	{
		content = fs.readFileSync('files/' + files[file],'utf8'); //will return a string since encoding mode was provided
		rows = content.split('\n');
		if(rows.length > 0)
		{
			for(row in rows)
			{
				console.log(`--- ${rows[row]}`);
			}			
		}
		else
		{
			console.log('--- no rows was found');
		}
	}
}
else
{
	console.log('no files found');	
}