File Handling

NodeJS

  • file reading
  • file appending

File Writing

  • require module called ‘fs’

module name = ‘fs’

fs.writeFile(file path, data, callback)

  • 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)

  • 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.appendFile is append the data in a exist file.

fs.appendFile(file path, data, callback)

  • 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

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