File Handling

Cho Zin Thet
1 min readJan 26, 2021

NodeJS

  • file writing
  • file reading
  • file appending

File Writing

  • create app.js in a folder.
  • require module called ‘fs’

module name = ‘fs’

fs.writeFile(file path, data, callback)

  • file path -> note.txt
  • data -> ‘Hello NodeJS’
//app.js
const fs = require('fs');
fs.writeFile('note.txt', 'Hello NodeJS', (err) => {
if(!err){
console.log('successful')
}else{
console.log(err);
}
})

Run app.js with the command

$ node app.js

You will see a new file called note.txt with the text ‘Hello NodeJS’ .

File Reading

fs.readFile(file path, options, callback)

  • file path -> note.txt
  • options -> ‘utf-8’ (option that we gonna read the file)
//app.js
const fs = require('fs');fs.readFile('note.txt', 'utf-8', (err, data) => {
if(!err){
console.log(data)
}else{
console.log(err)
}
})

Run app.js with the command. You will see the data that we have written.

$ node app
Hello NodeJS

File Appending

  • fs.writeFile search the file that match with name of file in the parameter. If no match file create new file and write data that we pass as a parameter. If there is same file , delete all data in there and replace with the data that we currently pass in.
  • fs.appendFile is append the data in a exist file.

fs.appendFile(file path, data, callback)

  • file path -> note.txt
  • data-> ‘Hello User!’
//app.js
const fs = require('fs');fs.appendFile('note.txt', 'Hello User!', (err) => {
if(!err){
console.log('successful');
}else{
console.log(err)
}
})

Run app.js with the command

$ node app.js

You will see a new file called note.txt as follow

Hello  NodeJSHello User!

--

--