Vicky Vargas Vicky Vargas - 1 year ago 350
Node.js Question

fs.readFileSync always returns empty string

I have a script that writes data from an API to some files. I have an object the contains the file descriptors for each file:

var csvFds = {
'file1' : null,
'file2' : null,
'file3' : null,
'file4' : null

for (var file in csvFds) {

var dirPath = __dirname + '/files/' + file;

try {
catch (e) {
mkdirp.sync(dirPath, {mode: 0755});

csvFds[file] = fs.openSync(dirPath + '/' + moment().format("YYYY-MM-DDTHH:mm:ss[Z]") + '.csv', 'a+');

Then I have some code that uses fs.write to write lines of csv to the file in batches. This part is working fine. I have well formed csv files. Now I need to read the contents of the entire file as a string. This is how I'm trying to do it:


But for some reason I am always getting an empty string. I have confirmed that fs.readFileSync is in fact returning a Buffer by using console.log and dropping the toString() method.

I'm really stuck on this so any help will be greatly appreciated. Thanks in advance. Here's some additional info regarding my node version and OS:

$ node -v

$ uname -a
Darwin i-2.local 14.5.0 Darwin Kernel Version 14.5.0: Thu Jun 16 19:58:21 PDT 2016; root:xnu-2782.50.4~1/RELEASE_X86_64 x86_64

Answer Source

Try to call readFileSync like this readFileSync(csvFds['file1'], 'utf-8'). It ought to return a string. Or you can omit the argument and then provide the encoding when calling toString method e.g. readFileSync(csvFds['file1']).toString('utf-8')

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download