How to use the rename function from graceful-fs

Find comprehensive JavaScript graceful-fs.rename code examples handpicked from public code repositorys.

graceful-fs.rename is a method in Node.js that allows you to rename a file or folder in a more reliable way than the standard fs.rename method.

0
1
2
3
4
5
6
7
8
9
10
var fs = require('graceful-fs')
var test = require('tap').test
var path = require('path')
var writeStream = require('../index.js')


var rename = fs.rename
fs.rename = function (from, to, cb) {
  setTimeout(function () {
    rename(from, to, cb)
  }, 100)
fork icon1
star icon1
watch icon0

22
23
24
25
26
27
28
29
30
31
32
33
  }
  fn.callCount = 0
  return fn
}


const originalRename = fs.rename


function setUpMockFs (errCode) {
  fs.rename = createAsyncErrFn(errCode)
}
fork icon802
star icon0
watch icon91

How does graceful-fs.rename work?

graceful-fs.rename() is a method provided by the graceful-fs module that is used to rename/move a file or directory asynchronously in a manner that handles errors and conflicts in a graceful manner. When used, the method checks for errors during the operation and retries the operation until it succeeds.

86
87
88
89
90
91
92
93
94
95
    moveIntoPlace()
  }
}

function moveIntoPlace () {
  fs.rename(writeStream.__atomicTmp, writeStream.__atomicTarget, iferr(trapWindowsEPERM, end))
}

function trapWindowsEPERM (err) {
  if (writeStream.__isWin &&
fork icon0
star icon0
watch icon0

149
150
151
152
153
154
155
156
157
158
      })
    })
  }
}).then(function rename () {
  return new Promise(function (resolve, reject) {
    fs.rename(tmpfile, truename, function (err) {
      if (err) reject(err)
      else resolve()
    })
  })
fork icon0
star icon0
watch icon0

+ 3 other calls in file

Ai Example

1
2
3
4
5
6
const fs = require("graceful-fs");

fs.rename("oldfile.txt", "newfile.txt", (err) => {
  if (err) throw err;
  console.log("File renamed successfully!");
});

In the above example, the rename function is called with two arguments - the first argument being the path to the file to be renamed, and the second argument being the new name of the file. The function takes a callback function as its third argument, which is called once the file has been renamed or an error has occurred. In the callback function, an error is thrown if one occurs, otherwise a success message is logged to the console.

9
10
11
12
13
14
15
16
17
18
19
20
var target3 = path.resolve(__dirname, 'test-rename-eperm3')


test('rename eperm none existing file', function (t) {
  t.plan(2)


  var _rename = fs.rename
  fs.existsSync = function (src) {
    return true
  }
  fs.rename = function (src, dest, cb) {
fork icon0
star icon0
watch icon0

+ 2 other calls in file