Thursday, September 25, 2025

Read from file and write to file

 Perform following steps,

  1. import path from 'path';
    • Need for path of files in order to access them
  2. import fs from 'fs';
    • Need for read and write on files
  3. In order to read or write, first we need to resolve the directory of the file
    • path.resolve(__dirname, 'directoryPath')
  4. For reading, need to parse before read (reading JSON file)
    • JSON.parse(fs.readFileSync(dirVar,'utf-8'))
  5. For writing, need to join the file name with directory (writing JSON file)
    • fs.writeFileSync( join(dirVar, 'filename'), JSON.stringify(contentVar) )

No comments:

Post a Comment