Search code examples
javascriptnode.jsstringfilebuffer

Node.js read a file as a string (not buffer) synchronously


How do I read a file in Node.js as a string and not as a buffer? I'm making a program in Node.js. There I need to read a file synchronously, but if I do that, it returns it as a buffer instead of a string. My code looks like that:

const fs = require('fs');

let content = fs.readFileSync('./foo.txt');
console.log(content) // actually logs it as a buffer

Please help.


Solution

  • fs.readFileSync takes a second parameter that allows you to specify an object with options, including the encoding of the returned data. If you do not specify one, it returns a Buffer by default. So, you would add the encoding to this example to return it as a String.

    Let's add the encoding option to this example where we set the content variable. We'll set the encoding to be UTF-8, which is a standard.

    let content = fs.readFileSync('./foo.txt', {encoding: 'utf8'});

    There is also a shortcut if you do not need to specify any other options:

    let content = fs.readFileSync('./foo.txt', 'utf8');

    Now when we log content, we should have a String as the result which we use.

    Official Documentation: https://nodejs.org/api/fs.html#fs_fs_readfilesync_path_options