kipenzam
kipenzam

Reputation: 127

readFileSync returns undefined

I have a 2MB html file, and node couldn't read that.

what I've tried:

const fs = require('fs');
const file_name = process.argv[2];

let blob = fs.readFileSync(file_name, 'utf8')
console.log(blob)

this prints 'undefined' to terminal

I've tried unsynchronous version, too:

const fs = require('fs');
const file_name = process.argv[2];

fs.readFile(file_name, 'utf8', function (err, data) {
    if (err) {
        console.log(err)
        return false    
    }
    console.log(data)
});

this prints 'undefined', too

when I tried other html files, it worked without any problem.

what can I do? is there any specific string pattern causes that node cannot read file?

Upvotes: 1

Views: 5187

Answers (2)

Sanchonn
Sanchonn

Reputation: 169

Try to use full path to the file

For example

// Dependencies
const fs = require('fs');
const path = require('path');
// Add current path to filename
const file_name = path.join(__dirname, process.argv[2]);

// Check if file exist
fs.exists(file_name, function (file) {
  if (file) {
    // Read file with file_name
    fs.readFile(file_name, 'utf8', function (err, data) {
      if (err) {
        console.log(err);
        return false;
      }
      console.log(data);
    });
  }
  else{
      console.log("file not found");
      return false;
  }
});

Upvotes: 1

Malay M
Malay M

Reputation: 1759

instead of using fs.readFile you can use fs.readFileSync('./db/user.json'); inside a try ... catch block.

const fetchAllUser = () => {

    // if file doesn't exists we have to write try catch
    try {
        // path should be relative to app.js / index.js (entry file)
        let userString = fs.readFileSync('./db/user.json');
        return JSON.parse(userString);
    } catch (e) {
        console.log(`No database available`);
        return [];
    }
};

Upvotes: 1

Related Questions