Skip to content

Node File System

Manipulating Files

Modifying the files are a very common programming task. Node.js core API provides methods to make modifying a files as a trivial. There are a variety of file system methods, all contained in the fs module.

To use this module:

1
const fs = require('fs')

A few available functions

fs simply provides a wrapper for the standard file operations, like:

  • fs.readFileSync() to read files synchronously
  • fs.readFile() to read files asynchronously
  • fs.watch() for watching changes in files
  • fs.exists() for checking that file exist
  • fs.open() for opening the file
  • fs.stat() for getting file attributes
  • fs.read() for reading chuck of data from the file
  • fs.writeFile() for writing to file
  • fs.close() for closing the file

Read file

Create input.txt file and store Sample text line in the file. string inside it.

1
2
// input.txt
Sample text line in the file.

You can read the file with readFile function. (error, data) defines a callback function which will be called after a file reading has been finished.

1
2
3
4
5
6
fs.readFile('input.txt', (error, data) => {
   if (error) console.error(error)
   else console.log(data.toString())
})

console.log("Program ended")

Above programming will print the following lines to the console. Note how Line 6 will be called before the callback function will be called and line 2 or 3 has been executed.

1
2
Program ended
Sample text line in the file.

Write file

The easiest way to write to files in Node.js is to use the writeFile().

1
2
3
4
5
6
7
8
9
const content = 'Some content!';

fs.writeFile('test.txt', content, err => {
  if (err) {
    console.error(err);
  } else {
    console.log('File written successfully')
  }
});

By default, this API will replace the contents of the file if it does already exist. You can modify the default by specifying a flag.

1
fs.writeFile('test.txt', content, { flag: 'a+' }, err => {});

The flags you'll likely use are

Flag Description
r+ This flag opens the file for reading and writing
w+ This flag opens the file for reading and writing and it also positions the stream at the beginning of the file
w+ This flag opens the file for reading and writing and it also positions the stream at the beginning of the file
a+ This flag opens the file for reading and writing and it also positions the stream at the end of the file
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
const fs = require('fs')
const path = require("path")

if (process.argv.length <= 2) {
  console.log("Usage: node " + path.basename(__filename) + " string")
  process.exit(-1)
}

const content = process.argv[2] + '\r\n'

fs.writeFile('output.txt', content, { flag: 'a+' }, err => {
  if (err) {
    console.error(err);
  } else {
    console.log('String added to file successfully')
  }
});
console.log("Program ended")

Read more

Goals of this topic

Understand

  • Node File System