Asked 7 years ago
19 Jan 2017
Views 3186
jaydeep

jaydeep posted

why readFile return buffer in Node JS ?

why readFile return buffer in Node JS ?


var fs=require('fs');
fs.readFile(filePath, function (error, file) {
    if (error) return callback(error)
  console.log(file);
  })



what i got at console is
<Buffer 30 09 5f 64 65 62 75 67 5f 61 67 65 6e 74 26 31 09 5f 64 65 62 75 67 67 65 72 26 32 09 5f 68 74 74 70 5f 61 67 65 6e 74 26 33 09 5f 68 74 74
70 5f 63 ... >

it says i am buffer . and it should be file content

get same with readFileSync

var file=fs.readFileSync(filePath);
i got again buffer , so what is the issue with readFile and readFileSync ?
why readFile and readFileSync return buffer instead content ?
fs.writeFileSync("sam.txt","data is content"); always write proper content , dont write byte code , so it means writeFile and WriteFileSync dont care about the encoding mode. - noob  
Jan 19 '17 04:32
noob

noob
answered Nov 30 '-1 00:00

i tried something with differ type of encoding . it give same output . so is there encoding option is just need to be any string or what /.


console.log(fs.readFileSync('file.txt','utf8'));//utf8 encoding
console.log(fs.readFileSync('file.txt','binary'));//binary encoding
console.log(fs.readFileSync('file.txt','ascii'));//ascii encoding 


ascii , binary , utf8 all give same output for redFileSync and readFile .

Mitul Dabhi

Mitul Dabhi
answered Nov 30 '-1 00:00

you forgot to pass encoding type which is second argument , i passed utf8 for below code so pls check it work like charm


var fs=require('fs');
fs.readFile(filePath, 'utf8', getFile );

  function getFile (error, fileContent) {
    if (error) return callback(error)
    console.log(fileContent); 
  }


or

var fs=require('fs');
fileContent=fs.readFileSync(filePath, 'utf8');

readFile and readFileSync return buffer if you dont specify character encoding type .
Rasi

Rasi
answered Nov 30 '-1 00:00


Why readFile / readFileSync return Buffer instead of file Content ?
it is intended to make it possible to work with filesystems that allow for non-UTF-8 filenames. mostly NTFS and HFS+ file systems have utf-8 file encoded.so for that one can pass encode option to 'utf-8'

how to convert Buffer to proper File content ?
1. pass encode option to utf8

 fs.readFile(filePath, 'utf8', callback);


2. toString() will do conversion

 fs.readFileSync(filePath).toString();


Post Answer