File Handling

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!

--

--

--

Learning javascript and web-development

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

An Introduction to Three.js

Let’s all mock J(a)SON — Makers Day 3

How to add your own type definitions to DefinitelyTyped

How to Configure dom0 Memory in XenServer 6.1 and Later for performance

//platform.twitter.com/widgets.js from Twitter https://twitter.com/thepoolsideceo

Optimizing React Performance: Part II

Getting started with React Router

20 of the Best and Most Hilarious Programming Memes

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Cho Zin Thet

Cho Zin Thet

Learning javascript and web-development

More from Medium

GitLab commands for beginners and everyday users

My Docker problems — Networking & Volumes

How to Fork a Repository in GitHub

Docker to the rescue