Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 222
milkwood1 Avatar asked Dec 07 '18 16:12

milkwood1


2 Answers

fs.readFileSync takes a second parameter that allows you to specify a JSON 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

like image 126
Anthony Jesmok Avatar answered Oct 03 '22 23:10

Anthony Jesmok


Aside from passing encoding which will ensure you get a string and not a buffer, the options parameter of the fs.readFileSync function also allows you to pass in a flag.

The default flag of this method is "r", which opens the file for reading. If you're opening it for reading and writing, then you should pass in another flag - "r+".

Your code would look like this if you're opening the file for reading and writing and not just reading:

const content = fs.readFileSync('./foo.txt/', 'utf-8', 'r+');
console.log(content);

Since this is node.js, you should consider using the async fs.readFile function instead. You'll have to pass this a callback of course.

like image 36
Chukwualuka Chiama Avatar answered Oct 03 '22 23:10

Chukwualuka Chiama