How to use the rename function from fs

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

fs.rename() is a Node.js file system method that renames/moves a file or directory from one location to another.

107
108
109
110
111
112
113
114
115
116
```js
const fs = require('fs/promises');

(async function(from, to) {
  try {
    await fs.rename(from, to);
    const stats = await fs.stat(to);
    console.log(`stats: ${JSON.stringify(stats)}`);
  } catch (error) {
    console.error('there was an error:', error.message);
fork icon371
star icon0
watch icon78

23
24
25
26
27
28
29
30
31
32
* 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 icon192
star icon570
watch icon16

+ 5 other calls in file

How does fs.rename work?

fs.rename is a method in Node.js that is used to rename a file or folder asynchronously. The method takes two parameters - the current path of the file or folder and the new path that it should be renamed to. If the new path already exists, the method will replace it with the renamed file/folder.

27
28
29
30
31
32
33
34
35
 * @param {string} from 
 * @param {string} to 
 */
function renameAsync(from,to){
    console.log(from , '----->', to)
    fs.rename(from,to)
    // fs.renameSync(from,to)

}
fork icon424
star icon0
watch icon2

29
30
31
32
33
34
35
36
37
 * @param {string} to
 */
function renameAsync(from, to) {
        console.log(from, '----->', to)
        // @ts-ignore
        fs.rename(from, to, (err) => {
            if (err) throw err;
        })
        // fs.renameSync(from,to)
fork icon10
star icon243
watch icon17

Ai Example

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

// Rename the file "oldname.txt" to "newname.txt"
fs.rename("oldname.txt", "newname.txt", (err) => {
  if (err) throw err;
  console.log("File renamed!");
});

In this example, the fs.rename method is used to rename the file named "oldname.txt" to "newname.txt". The method takes three arguments: the current file name, the new file name, and a callback function to be called once the operation is complete. The callback function can be used to handle any errors that occur during the operation.

22
23
24
25
26
27
28
29
30
31
const readdirAsync = (path) => new Promise((resolve, reject) => {
    return fs.readdir(path, (err, filenames) => err ? reject(err) : resolve(filenames))
});

/**
 * Promisified version of fs.rename
 * 
 * @method renameAsync
 * 
 * @param {string} oldPath
fork icon7
star icon10
watch icon3

+ 3 other calls in file

295
296
297
298
299
300
301
302
303
304
  assert.strictEqual(err.syscall, 'rename');
  return true;
};

const destFile = path.join(tmpdir.path, 'foo');
fs.rename(nonexistentFile, destFile, common.mustCall(validateError));

assert.throws(
  () => fs.renameSync(nonexistentFile, destFile),
  validateError
fork icon42
star icon19
watch icon0

+ 3 other calls in file

230
231
232
233
234
235
236
237
238
239
if (re.test(files[file])) {
        console.log(files[file]);
        var oldPath = rootPath + files[file];
        var newPath = rootPath + files[file].substring(0, files[file].length - ext.length) + newExt;
        console.log(newPath);
        fs.rename(oldPath, 
                                newPath, 
                                function (err) {
                                        console.error("unable to rename file");
        });     
fork icon1
star icon0
watch icon2

-1
fork icon0
star icon12
watch icon4

68
69
70
71
72
73
74
75
76
77
78
const unlinkFile = (path, cb) => {
  if (!isWindows)
    return fs.unlink(path, cb)


  const name = path + '.DELETE.' + crypto.randomBytes(16).toString('hex')
  fs.rename(path, name, er => {
    if (er)
      return cb(er)
    fs.unlink(name, cb)
  })
fork icon3
star icon2
watch icon0

9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
        notification(`Renamed ${source} to ${filename}`)
    })

} else {

    fs.rename(source, filename, function (err) {
        if (!err) {

            notification(`Renamed ${source} to ${filename}`)
            return callback(1)
fork icon2
star icon5
watch icon1

26
27
28
29
30
31
32
33
34
35
let splitName = allFiles.name.split('.')
let splitPath = allFiles.path.split('_')
let fileName = splitPath[splitPath.length - 1]
let extName = '.' + splitName[splitName.length - 1]
let newPath = __dirname + '/uploadFile/' + fileName + extName
fs.rename(oldPath, newPath, function(err) {
  if (err) {
    console.log('fail: ' + err)
  }
})
fork icon0
star icon0
watch icon1

267
268
269
270
271
272
273
274
275
276
277
    const fn = swap(callback, msg);
    
    const fromRooted = root(from, rootDir);
    const toRooted = root(to, rootDir);
    
    return fs.rename(fromRooted, toRooted, fn);
}


function pack(from, to, names, config, fn) {
    const rootDir = config('root');
fork icon0
star icon0
watch icon1

+ 2 other calls in file

231
232
233
234
235
236
237
238
239
240
let path = `${userPath}/${AES.get(req.cookies.webnote)}/md/${req.body.topNavType}/${req.body.leftNavType}`
fs.access(`${path}/${req.body.mdName}.md`, fs.constants.F_OK, (err) => {
    if (err) {
        res.send({ code: 0, msg: `非法操作` })
    } else {
        fs.rename(`${path}/${req.body.mdName}.md`, `${path}/${req.body.newMdName}.md`, (err) => {
            if (err) {
                res.send({ code: 0, msg: `${req.body.mdName} 重命名失败,请稍后重试` })
            } else {
                res.send({ code: 1, msg: `${req.body.mdName} 已重命名为 ${req.body.newMdName} ` })
fork icon0
star icon0
watch icon1

605
606
607
608
609
610
611
612
613
614
    newALogPath = path.join(
        logLocation,
        `${y}/${doy}/activityLog.txt`
    );
}
fs.rename(
    oldALogPath,
    newALogPath,
    function (err) {
        if (err) throw err;
fork icon0
star icon0
watch icon1

130
131
132
133
134
135
136
137
138
139
request.on('end', function(){
    var post = qs.parse(body);
    var id = post.id;
    var title = post.title;
    var description = post.description;
    fs.rename(`data/${id}`, `data/${title}`, function(error){
      fs.writeFile(`data/${title}`, description, 'utf8', function(err){
        response.writeHead(302, {Location: `/?id=${title}`});
        response.end();
      })
fork icon0
star icon0
watch icon1

233
234
235
236
237
238
239
240
241
242
  clog.info('copy', source, 'to', target)
  fs.copyFile(source, target, cb)
},
move(source, target, cb=()=>{}){
  clog.info('move', source, 'to', target)
  fs.rename(source, target, cb)
},
rename(oldPath, newPath, cb=()=>{}){
  // AKA - move
  clog.info('rename', oldPath, 'to', newPath)
fork icon0
star icon0
watch icon1

+ 5 other calls in file

110
111
112
113
114
115
116
117
118
119
var post = qs.parse(body);
var id = post.id;
var title = post.title;
var description = sanitizeHtml(post.description);

fs.rename(`data/${id}`, `data/${title}`, (err) => {
  // console.log(err);
  fs.writeFile(`data/${title}`, description, 'utf8', err => {
    if (err) {
      // console.error(err);
fork icon0
star icon0
watch icon1

181
182
183
184
185
186
187
188
189
190
        //                 if (err) {
        //                     console.log(err)
        //                     return
        //                 }
        //             })
        fs.rename(path + '/' + filename, path + '/' + filename.replaceAll('!@#', ''), function (err) {
                if (err) throw err;
                console.log('File Renamed!');
        });
} catch (err) {
fork icon0
star icon0
watch icon1

126
127
128
129
130
131
132
133
134
135
request.on("end", function () {
  var post = qs.parse(body);
  var id = post.id;
  var title = post.title;
  var description = post.description;
  fs.rename(`data/${id}`, `data/${title}`, function (error) {
    fs.writeFile(`data/${title}`, description, "utf8", function (err) {
      response.writeHead(302, { Location: `/?id=${title}` });
      response.end();
    });
fork icon0
star icon0
watch icon1

50
51
52
53
54
55
56
57
58
59
60
}


Adapter.prototype.save = function(name, options, next, cb){
    var url = path.join(this.root, name+(this.filetype?'.'+this.filetype:''));
    var backUrl = path.join(this.root, name+'.bak'+(this.filetype?'.'+this.filetype:''));
    fs.rename(url, backUrl, function(err){
        //todo: handle errors by reverting
        var writtenOne = false;
        var writeChain = function(callback){
            var item = next();
fork icon0
star icon0
watch icon2