node readFileSync code example

Example 1: readfilesync

const fs = require('fs')

try {
  const data = fs.readFileSync('/Users/joe/test.txt', 'utf8')
  console.log(data)
} catch (err) {
  console.error(err)
}

Example 2: nodejs readfile

const fs = require('fs');

fs.readFile('/Users/joe/test.txt', 'utf8' , (err, data) => {
  if (err) {
    console.error(err);
    return
  }
  console.log(data);
});

Example 3: node readFileSync json

const fs = require('fs');

let rawdata = fs.readFileSync('student.json');
let student = JSON.parse(rawdata);
console.log(student);

Example 4: fs.readfile

fs.readFile('filename', function read(err, data) {
    if (err) {
        throw err;
    }
    var content = data;
  
    console.log(content);  
   
});

Example 5: node read file sync

// macOS, Linux, and Windows
fs.readFileSync('<directory>');
// => [Error: EISDIR: illegal operation on a directory, read <directory>]

//  FreeBSD
fs.readFileSync('<directory>'); // => <data>

Example 6: readfilesync return buffer

squadJSON = JSON.parse(fs.readFileSync('./squads/squad' + whichSquad + '.json', 'utf8'));