【问题标题】:nodejs not creating the file that specified using fs.open and throwing error 4058-ENOENTnodejs 没有创建使用 fs.open 指定的文件并抛出错误 4058-ENOENT
【发布时间】:2018-12-25 21:07:08
【问题描述】:

我正在使用这段代码来创建和编写一个新目录和一个文件。 我刚开始学习nodejs

var lib = {};

lib.baseDir = path.join(__dirname,'/../.data/');

lib.create = function(dir,file,data,callback){

fs.open(lib.baseDir+dir+'/'+file+'.json', 'wx', function(err, fileDescriptor){

if(!err && fileDescriptor){

  var stringData = JSON.stringify(data);

  // Write to file and close it
  fs.writeFile(fileDescriptor, stringData,function(err){
    if(!err){
      fs.close(fileDescriptor,function(err){
        if(!err){
          callback(false);
        } else {
          callback('Error closing new file');
        }
      });
    } else {
      callback('Error writing to new file'+'lib.baseDir');
    }
  });
} else {
  callback(err);
  }
 });
};

但我反复收到错误

{ Error: ENOENT: no such file or directory, open 'C:\Users\Jawahr\Documents\GitHub\node-api\.data\test\newFile.json'
errno: -4058,
code: 'ENOENT',
syscall: 'open',
path: 'C:\\Users\\Jawahr\\Documents\\GitHub\\node- 
api\\.data\\test\\newFile.json' }

在 index.js 中调用这个库

var _data = require('./lib/data');

_data.create('test','newFile', {"asdksadlk" : "asldj"} ,function(err) {
  console.log('this was the error ',err);
});

我已经在这里停留了一段时间,是因为pathnamefilename 包含"C:" 部分,它在Windows 10 中具有冒号一个保留字符,如果是如何解决这个问题。

使用 Windows 10 和 NodeJs 8.6。

【问题讨论】:

标签: javascript node.js windows fs


【解决方案1】:

你可以试试这个 -

fs.open(lib.baseDir+dir+'/'+file+'.json', 'w', function(err, fileDescriptor){

如果文件存在,'wx' 似乎会引发错误 -

'w' - Open file for writing. The file is created (if it does not exist) or truncated (if it exists).

'wx' - Like 'w' but fails if the path exists.

'w+' - Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists).

'wx+' - Like 'w+' but fails if the path exists.

转自here

【讨论】:

  • 不。当新文件的路径不存在时,fs.open(...) 会抛出错误。
  • 检查C:\Users\Jawahr\Documents\GitHub\node-api\.data\test目录的存在和访问权限
  • 但是 node fs.open() 会在没有该名称的文件和目录时自动创建一个文件和目录,对不起,如果我错了,请纠正我
  • fs.open() 如果文件不存在则创建文件,但不会创建目录。在不显式创建文件的情况下尝试在一些现有目录中。
【解决方案2】:

看起来您的文件路径不存在或不可访问。看:

fs.open('/path/is/not/exists/xx.js','wx',(err,fd)=>{
    if (err) {
      console.log(err.message);
    }
});

得到了

 Error: ENOENT: no such file or directory, open '/path/is/not/exists/xx.js'

如果文件已经存在,你会得到类似Error: EEXIST: file already exists, open '...'

最后,但并非最不重要。而不是lib.baseDir+dir+'/'+file+'.json' 更好的解决方案是使用来自path 模块的path.join(lib.baseDir,dir,file+'.json')

【讨论】:

    【解决方案3】:

    在 fs.open 之前添加目录检查或创建

    if (!fs.existsSync(dir)){
        fs.mkdirSync(dir);
    }
    

    然后您的其余代码将起作用。因为 fs.open 仅在文件不存在时创建文件,它不创建目录

    【讨论】:

      猜你喜欢
      • 2016-08-10
      • 1970-01-01
      • 1970-01-01
      • 2012-04-02
      • 2020-09-20
      • 2021-05-21
      • 1970-01-01
      • 2017-12-25
      • 1970-01-01
      相关资源
      最近更新 更多