简体   繁体   中英

How to read file in Node?

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);
    });
}
});

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM