Reading and Writing files with Node.js

In this post I’m going to show you how we can read and write files on our local filesystem using Node.js.

Being able to read files from you local filesystem can be very useful and there’s a buntch of stuff you can do with it, for example read local Json files and load Spreadsheets to your program.

To start, just create a js file and name it whatever you want. Then open this file in your editor of choice.

Reading from files is done via the core fs module. The fs module provides an API for interacting with the file system in a manner closely modeled around standard POSIX functions.

To use this module, add this line to your file:

const fs = require('fs');

I’m also using a very usefull package called Path to join path on the local filesystem, so also add this module to you file:

var path = require('path');

All file system operations have synchronous and asynchronous methods. The asynchronous form always takes a completion callback as its last argument. The arguments passed to the completion callback depend on the method, but the first argument is always reserved for an exception. If the operation was completed successfully, then the first argument will be null or undefined.

In most cases developers should use asynchronous methods because Node won’t stop execution to wait for I/O operations.

var fs = require('fs');
var path = require('path');
fs.readFile(path.join(__dirname, '/data/customers.csv'), {encoding: 'utf-8'}, (err, data) => {
if (err) throw err;

If you want this operation to be async then just use readFileSync instead of readFile.

And the writing to the file:

var fs = require('fs');
fs.writeFile('message.txt', 'Hello World!', function (err) {
if (err) throw err;
console.log('Writing is done.');

And that’s it for reading and writing files on the filesystem with Node.js. I hope you enjoyed this, see you soon!

Leave a comment

Leave a Reply