How to use the rename function from fs-extra

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

fs-extra.rename is a function in the fs-extra library that allows you to rename/move a file or directory asynchronously.

256
257
258
259
260
261
262
263
264
265
266
		await events.once(pipe, "finish");
		await fs.fsync(fd);
	} finally {
		await fs.close(fd);
	}
	await fs.rename(tempSavePath, savePath);
}


module.exports = {
	patch,
fork icon58
star icon228
watch icon0

146
147
148
149
150
151
152
153
154
155
156
157
158
		await fs.fsync(fd);
	} finally {
		await fs.close(fd);
	}


	await fs.rename(temporary, file);
}




// Reserved names by allmost all filesystems
fork icon58
star icon228
watch icon0

How does fs-extra.rename work?

The fs-extra.rename() method in Node.js provides a way to rename files and directories asynchronously, with additional functionality such as preserving file timestamps and permissions, and automatically creating destination directories if they don't exist. When renaming a file or directory, you can also provide a callback function to be called upon completion.

71
72
73
74
75
76
77
78
79
80
    "Contents",
    "MacOS",
    binaryName
  )
);
await fs.rename(
  path.resolve(
    process.cwd(),
    `${appDistributionName}.app`,
    "Contents",
fork icon15
star icon187
watch icon0

447
448
449
450
451
452
453
454
455
456
var delete_file_path = path.join(delete_path, filename); // The full path to be moved to
if (owner == username || permission == "admin") {
   if (!utils.directoryExists(delete_path)) {
      utils.mkdirpSync(delete_path); // Creates the directory if it doesn't already exist
   }
   fs.rename(file_path, delete_file_path, function(err) { // Moves the file to the deleted cache
      if (err) {
         utils.handleError(err, res);
      } else {
         // TODO change to res.json
fork icon29
star icon68
watch icon15

+ 7 other calls in file

Ai Example

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

fs.rename("/path/to/oldfile.txt", "/path/to/newfile.txt")
  .then(() => console.log("File renamed successfully"))
  .catch((err) => console.error(err));

This code renames the file /path/to/oldfile.txt to /path/to/newfile.txt using the fs-extra.rename method. If the operation is successful, the message "File renamed successfully" will be logged to the console. If an error occurs, the error object will be logged to the console instead.

474
475
476
477
478
479
480
481
482
483
fillPartition(10);
partition.close();

let reader = createReader();
reader.open();
fs.rename(reader.fileName, reader.fileName + '2', () => {
    setTimeout(() => {
        expect(reader.isOpen()).to.be(false);
        done();
    }, 5);
fork icon4
star icon31
watch icon0

+ 5 other calls in file

386
387
388
389
390
391
392
393
394
395

if (req.file) {
  // An attachment was uploaded
  await fs.ensureDir(dir)
  await fs.emptyDir(dir)
  await fs.rename(req.file.path, path.join(dir, req.file.originalname))
  const relativePath = path.join(lineId, req.file.originalname)
  const pathField = req.dataset.schema.find(f => f['x-refersTo'] === 'http://schema.org/DigitalDocument')
  if (!pathField) {
    throw createError(400, 'Le schéma ne prévoit pas d\'associer une pièce jointe')
fork icon6
star icon26
watch icon4

+ 3 other calls in file

237
238
239
240
241
242
243
244
245
246
- fs.open():设置文件模式
- fs.readdir():读取目录的内容
- fs.readFile():读取文件的内容。有关:fs.read()
- fs.readlink():读取符号链接的值
- fs.realpath():将相对文件路径指针(.,..)解析为完整路径
- fs.rename():重命名文件或文件夹
- fs.rmdir():删除文件夹
- fs.stat():返回由传递的文件名标识的文件的状态。相关阅读:fs.fstat(),fs.lstat()
- fs.symlink():创建指向文件的新符号链接
- fs.truncate():将传递的文件名标识的文件截断为指定的长度。有关:fs.ftruncate()
fork icon0
star icon12
watch icon1

+ 13 other calls in file

151
152
153
154
155
156
157
158
159
    return FS.outputFile(tmpPath, data, function (err) {
        if (err) return callback(err);
        // Assume file exists.
        return FS.unlink(path, function () {
                // We ignore error.
                return FS.rename(tmpPath, path, callback);
        });
    });
}
fork icon2
star icon10
watch icon3

+ 13 other calls in file

159
160
161
162
163
164
165
166
167
168
```js
const fs = require('fs/promises')

async function example() {
  try {
    await fs.rename('/Users/joe', '/Users/roger')
  } catch (err) {
    console.log(err)
  }
}
fork icon5
star icon1
watch icon1

194
195
196
197
198
199
200
201
202
203
}

try {
    await fs.writeFile(appSaveInfo.appSavePath + '/' + app.app + '.plist', app.plist);
    await fs.writeFile(appSaveInfo.appSavePath + '/' + app.app + '.plist.json', JSON.stringify(app.parsedPlist));
    await fs.rename(app.filename, appSaveInfo.appSavePath + '/' + app.app + '.ipa');
} catch (err) {
    logger.debug('Attempting to remove created dir');
    await fs.rmdir(appSaveInfo.appSavePath).catch(logger.warning);
    return Promise.reject(`Moving failed with err: ${err}`);
fork icon3
star icon3
watch icon2

+ 9 other calls in file

244
245
246
247
248
249
250
251
252
253
254
255
));


// copy copies the built artifacts in build into dist/
gulp.task('copy', (callback) => {
  // Explicitly do not use gulp here. It's too slow and messes up the symlinks
  fs.rename('build', DIST, callback);
});


// minify:css minifies the css
gulp.task('minify:css', () => {
fork icon1
star icon8
watch icon1

+ 3 other calls in file

956
957
958
959
960
961
962
963
964
965
async function rename({
	name,
	newName,
}) {
	try {
		return await fs.rename(name, newName)
		.then((result) => result)
		.catch((error) => {
			return { 
				error: 'Попробуй другое название' 
fork icon0
star icon2
watch icon1

+ 19 other calls in file

8334
8335
8336
8337
8338
8339
8340
8341
8342
8343

function doRename () {
  if (path.resolve(src) === path.resolve(dest)) {
    fs.access(src, callback)
  } else if (overwrite) {
    fs.rename(src, dest, err => {
      if (!err) return callback()

      if (err.code === 'ENOTEMPTY' || err.code === 'EEXIST') {
        remove(dest, err => {
fork icon0
star icon1
watch icon0

+ 8 other calls in file

74
75
76
77
78
79
80
81
82
83
84
85
    return err ? _.fail(err, callback) : _.done(src, callback)
  })
}


function copy(src, dest, callback) { return fs.copy(src, dest, _.cb(callback)) }
function rename(src, dest, callback) { return fs.rename(src, dest, _.cb(callback)) }
function remove(src, callback) { return fs.remove(src, _.cb(callback)) }
function move(src, dest, callback) { return fs.move(src, dest, _.cb(callback)) }


function dirPaths(src, callback) {
fork icon0
star icon0
watch icon0

+ 9 other calls in file

293
294
295
296
297
298
299
300
301
302
  }
}

async renameAppAndHelpers () {
  await this.moveHelpers()
  await fs.rename(this.electronAppPath, this.renamedAppPath)
}

async signAppIfSpecified () {
  const osxSignOpt = this.opts.osxSign
fork icon0
star icon0
watch icon0

+ 8 other calls in file

71
72
73
74
75
76
77
78
79
80
  return path.join(this.originalResourcesDir, 'app.asar')
}

async relativeRename (basePath, oldName, newName) {
  debug(`Renaming ${oldName} to ${newName} in ${basePath}`)
  await fs.rename(path.join(basePath, oldName), path.join(basePath, newName))
}

async renameElectron () {
  return this.relativeRename(this.electronBinaryDir, this.originalElectronName, this.newElectronName)
fork icon0
star icon0
watch icon0

+ 8 other calls in file

2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
// console.log(files[i]);
if(files[i]!=='.DS_Store'&&files[i]!=='DICOMDIR'){
    let curFile = path.join(currentPath, files[i]);      
        if (fs.statSync(curFile).isFile()&&path.extname(curFile)!=='.jpg') {   
            total+=1;
            fs.rename(curFile, curFile+'.dcm', function (err) {
                if (err) throw err;
            });
        } else if (fs.statSync(curFile).isDirectory()) {
            walkDir(curFile);
fork icon0
star icon0
watch icon3

+ 29 other calls in file

240
241
242
243
244
245
246
247
248
249
250
251
));


// copy copies the built artifacts in build into dist/
gulp.task('copy', (callback) => {
  // Explicitly do not use gulp here. It's too slow and messes up the symlinks
  fs.rename('build', 'dist', callback);
});


// minify:css minifies the css
gulp.task('minify:css', () => {
fork icon0
star icon0
watch icon0

37
38
39
40
41
42
43
44
45
    await exec(`unzip -o ${file} -d ${dir}`)
  } catch (err) {
    log.warning(err)
  }
  const fileXML = (await fs.readdir(dir)).filter(file => file.endsWith('.xml') && file.toUpperCase().includes('CARBURANT'))
  await fs.rename(path.join(dir, fileXML[0]), path.join(dir, 'carburants.xml'))
  // remove the zip file
  await fs.remove(file)
}
fork icon0
star icon0
watch icon0

384
385
386
387
388
389
390
391
392
393
  }
  throw e;
} finally {
  if (log) {
    await log.close();
    await fs.rename(logFile, logFile.replace('.txt', '.final.txt'));
  }
  if (tempScript) {
    if (fs.unlinkSync(tempScript)) {
      fs.unlinkSync(tempScript);
fork icon0
star icon0
watch icon0

function icon

fs-extra.readFileSync is the most popular function in fs-extra (9724 examples)