Home > Net >  Delete specific rows from a text file in NodeJS
Delete specific rows from a text file in NodeJS

Time:10-22

I am trying to delete a specific row from a text file using NodeJs, but I am having trouble to do so. Can anyone please help me?

This is the content inside the text file and I am trying to delete example3:example3 from the text file.

example1:example1
example2:example2
example3:example3
example4:example4

This is the code that should work but doesn't

const fs = require('fs')
const path = require('path')

const filePath = path.join(__dirname, '../data/test.txt')
const fileData = fs.readFileSync(filePath, 'utf-8').split('\r\n')

const position = 3

fileData.splice(position - 1, 1)

CodePudding user response:

You need to save the file with fs.writeFile or fs.writeFileSync

Synchronous:

const fs = require('fs')
const path = require('path')
const filePath = '../data/test.txt'

const filePath = path.join(__dirname, filePath)
const fileData = fs.readFileSync(filePath, 'utf-8').split('\r\n')

const position = 3

fileData.splice(position - 1, 1)
const dataString = fileData.join('\r\n')
fs.writeFileSync(filePath, dataString)

Asynchronous:

const fs = require('fs')
const path = require('path')
const filePath = '../data/test.txt'

const filePath = path.join(__dirname, filePath )

fs.readFile(filePath, (err, data) => {
  if (err) throw err

  const fileData a data.split('\r\n')

  const position = 3

  fileData.splice(position - 1, 1)
  const dataString = fileData.join('\r\n')

  fs.writeFile(filePath, dataString, (err) => {
    if (err) throw err
    else console.log('file saved')
  })
})


  • Related