简体   繁体   English

如何在Node中读取文件?

[英]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. 我想读取文件,但是如果文件在特定路径上不可用,则给出错误。我想创建一个文件(如果不存在),并且获取数据值为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". 错误是在“编码utf”中。 It should be an object. 它应该是一个对象。

See: http://nodejs.org/api/fs.html#fs_fs_readfile_filename_options_callback 请参阅: 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, '');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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