0

Problem Statement:

Complete function readFile to read the contents of the file sample.txt and return the content as plain text response.

Note: make sure when you read file mention its full path. for e.g - suppose you have to read file xyz.txt then instead of writing './xyz.txt' or 'xyz.txt' write like ${__dirname}/xyz.txt

My Code:

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

let readFile = () => {

let file = path.join(__dirname,'/xyz.txt') ;
let variableFile = fs.readFileSync(file);
return variableFile.toString();
};

module.exports = {

    readFile:readFile

};
Manab Das
  • 111
  • 1
  • 4

1 Answers1

0

You have to pass an encoding parameter to readFileSync or it will return a buffer:

const variableFile = fs.readFileSync(file,  "utf8");
return variableFile;

PS: You should not use synchronous calls in production, there is a very neat API called "promisify" that allows you to use async/await or promises with fs:

const {promisify} = require('util');
const fs = require('fs');
const readFile = promisify(fs.readFile);

const example = async () => {
    const file = await readFile(/*...*/);
}
Alexandre Senges
  • 1,474
  • 1
  • 13
  • 22