0

I want to read file but if file not available on particular path than gives an error.I want to create a file if not exist and get data value is null. I used these code but not working please any one help me?

fs.readFile(path, 'utf8', function (err,data) {
if (err) {
  return console.log(err);  //Here throw error if not available
}
 console.log(data);
 fileData = data;
});

I used below code it's also not working.I want read all data from file what should i put on '?' in following code?

fs.open(path, 'w+', function(err, data) {
if (err) {
    console.log("ERROR !! " +err);
} else {
    fs.read(data, ? , 0, ? , null, function(err) {
        if (err) console.log("ERROR !! " +err);
    });
}
});

2 Answers 2

1

There is an error in your first code snippet, try:

fs.readFile(path, {encoding: 'utf8'}, function (err, data) {
  if (err) throw err;
   console.log(data);
 });

The error was in the "encoding utf". It should be an object.

See: http://nodejs.org/api/fs.html#fs_fs_readfile_filename_options_callback

Sign up to request clarification or add additional context in comments.

Comments

0
if(fs.existsSync(file_path))
{
   var file_content = fs.readFileSync(file_path, 'utf-8');
} else {
   var file_content = fs.writeFileSync(file_path, '');
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.