简体   繁体   English

如果文件已经存在,如何在fs.rename命令上触发错误?

[英]How to trigger error on fs.rename command if file already exists?

I have the following code that moves files from one directory to another: 我有以下代码将文件从一个目录移动到另一个目录:

var fs = require('fs'),
    oldPath = 'firstfile.txt',
    newPath = 'temp/firstfile.txt';

fs.rename(oldPath, newPath, function (err) {
    console.log('rename callback ', err); 
});

Is it possible to trigger error if newPath file already exists? 如果newPath文件已经存在,是否可以触发错误?

Try this peice of Code below: 试试下面的代码:

It called the .exists method which check if a path exists or not 它调用了.exists方法,该方法检查路径是否存在

var fs = require('fs'),
    oldPath = 'firstfile.txt',
    newPath = 'temp/firstfile.txt';

fs.exists(newPath, function(exists){
 if (!exists) {
   fs.rename(oldPath, newPath, function (err) {
     console.log('rename callback ', err); 
   });
 } else {
   console.log('The File Already exists');
 }
});

Indeed, you need to do it in one instruction to avoid the race condition (as explained in the comments). 确实,您需要在一条指令中执行此操作以避免竞争情况(如注释中所述)。

There is at my knowledge no way to do it with the core fs library, but there is a function for doing it in the extended version . 据我所知,无法使用核心fs库执行此操作,但是在扩展版本中可以使用此功能。

See the move function, whose default behavior doesen't allow to overwride files: 请参见移动功能,其默认行为不允许覆盖文件:

https://github.com/jprichardson/node-fs-extra/blob/master/docs/move.md https://github.com/jprichardson/node-fs-extra/blob/master/docs/move.md

const fs = require('fs-extra')

fs.move('/tmp/somefile', '/tmp/does/not/exist/yet/somefile', err => {
  if (err) return console.error(err)

  console.log('success!')
})

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

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