How to use the moveSync function from fs-extra

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

fs-extra.moveSync is a function in the fs-extra library that allows a user to synchronously move a file or directory to a new location.

286
287
288
289
290
291
292
293
294
295
// TODO Need to find a way to make this more robust for when folder rename fails
// Check whether the url has been changed. If so, rename the folder
if ( this.oldUrl !== undefined && this.oldUrl !== '' && this.url !== this.oldUrl ) {
    // rename (move) folder if possible - but don't overwrite
    try {
        fs.moveSync(path.join(/** @type {string} */ (uib.rootFolder), this.oldUrl), this.customFolder, { overwrite: false })
        log.trace(`[uibuilder:nodeInstance:${this.url}] Folder renamed from ${this.oldUrl} to ${this.url}`)
        // Notify other nodes
        tiEvents.emit(`node-red-contrib-uibuilder/URL-change/${this.oldUrl}`, { oldURL: this.oldUrl, newURL: this.url, folder: this.customFolder } )
    } catch (e) {
fork icon75
star icon352
watch icon25

+ 12 other calls in file

383
384
385
386
387
388
389
390
391
392
393
394


  const pathsInSource = await fsPromises.readdir(source, { withFileTypes: true })


  pathsInSource.forEach(function (entry) {
    if (entry.name !== 'app') {
      fs.moveSync(source + fsPath.sep + entry.name, destination + fsPath.sep + entry.name)
    }
  })
}

fork icon39
star icon105
watch icon0

How does fs-extra.moveSync work?

fs-extra.moveSync is a synchronous function in the fs-extra library that moves a file or directory from one location to another. The function accepts two arguments: the path to the source file/directory and the path to the destination directory/file. If the destination is an existing directory, the source is moved into that directory; otherwise, the source is renamed to the destination name and moved to the directory that contains it.

The function also accepts an optional options object that can include various settings such as the overwrite flag to determine whether to overwrite an existing file/directory or not, and the set of options to pass to the fs.copyFileSync function if it is used during the move operation.

Once called, fs-extra.moveSync blocks further execution of the program until the move operation is complete. If the move operation fails, an error is thrown.

It is important to note that fs-extra.moveSync is a synchronous function, which means that it will block the event loop until the operation is complete. Therefore, it should be used carefully, especially when dealing with large files or directories, to avoid causing performance issues or even crashing the program.

476
477
478
479
480
481
482
483
484
485
    if (err) {
      fs.removeSync(localPathTmp);
      return callback(new E('EClient', 'Load Script Market failed', { message: err.toString() }));
    }

    fs.moveSync(localPathTmp, localPath, { overwrite: true });
    fs.removeSync(localPathTmp);
    return callback();
  });
},
fork icon34
star icon185
watch icon0

147
148
149
150
151
152
153
154
155
  writeStream.on("error", (err) => {
    console.log("this is the writeStream error ", err);
  });
  fs.ensureDirSync(resultDirNegative); // Make sure destination folder exists, if not, create it
  fs.removeSync(resultPathNegative);
  fs.moveSync(resultPathPositive, resultPathNegative, false);
  console.log(`\t Create diff image [negative]: ${diffFile}`);
} else {
  diffFile = `${diffDirPositive}${filename}`;
fork icon29
star icon40
watch icon4

+ 3 other calls in file

Ai Example

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

// Move file from `dir1/file.txt` to `dir2/file.txt`
fs.moveSync("dir1/file.txt", "dir2/file.txt");

In the example above, the fs-extra.moveSync method is used to move a file called file.txt from the dir1 directory to the dir2 directory. The method call is synchronous, meaning that the file move operation will block execution until it is complete.

131
132
133
134
135
136
137
138
139
140

if(!fs.existsSync(configPath)){
    // Create all parent directories.
    fs.ensureDirSync(path.join(configPath, '..'))
    if(fs.existsSync(configPathLEGACY)){
        fs.moveSync(configPathLEGACY, configPath)
    } else {
        doLoad = false
        config = DEFAULT_CONFIG
        exports.save()
fork icon2
star icon1
watch icon0

+ 3 other calls in file

267
268
269
270
271
272
273
274
275
276
  fs.appendFileSync(path.join(appPath, '.gitignore'), data);
  fs.unlinkSync(path.join(appPath, 'gitignore'));
} else {
  // Rename gitignore after the fact to prevent npm from renaming it to .npmignore
  // See: https://github.com/npm/npm/issues/1862
  fs.moveSync(
    path.join(appPath, 'gitignore'),
    path.join(appPath, '.gitignore'),
    []
  );
fork icon1
star icon0
watch icon2

+ 4 other calls in file

98
99
100
101
102
103
104
105
106
107

    localRmSync("upgrade-nobejs", { recursive: true });
    localRmSync("core_bk", { recursive: true });
  } catch (err) {
    localRmSync("core", { recursive: true });
    fs.moveSync(path.resolve(`core_bk`), path.resolve(`core`));

    console.log("err", err);
  }
});
fork icon1
star icon0
watch icon1

+ 35 other calls in file

25
26
27
28
29
30
31
32
33
34
35
            } else {
                throw new Error(`'${targetPath}' is already linked to another directory`);
            }
        }


        fs.moveSync(sourcePath, targetPath);
        fs.symlinkSync(targetPath, sourcePath, "junction");
        console.log(`Linked ${sourcePath} <==> ${targetPath}`);
    }
})().catch(error => {
fork icon1
star icon0
watch icon1

+ 9 other calls in file

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


function moveFile(sourcePath, destFolder) {
  try {
    let fileName = getFileName(sourcePath);
    fse.moveSync(sourcePath, destFolder + fileName);
    return true;
  } catch (err) {
    console.error(err);
    return false;
fork icon0
star icon8
watch icon2

+ 4 other calls in file

158
159
160
161
162
163
164
165
166
  ].forEach(projectName => {
    move(path.resolve(serverJvmRoot, projectName), path.resolve(serverJvmRoot, projectName.replace(appNamePlaceholder, data.appName)));
  });


  function move(oldPath, newPath) {
    fs.moveSync(oldPath, newPath, {overwrite: data.forceOverwrite});
  }
};
fork icon0
star icon3
watch icon2

+ 12 other calls in file

231
232
233
234
235
236
237
238
239
240
241
242
    }
  }
}


function crossDeviceRenameSync(source, destination) {
  return fse.moveSync(source, destination, {overwrite: true});
}


/*
 * Grabs the built packages in ${tmp_build_dir}/node_modules and updates the
fork icon0
star icon1
watch icon1

81
82
83
84
85
86
87
88
89
90

if (lastChunk) {
  filename = Date.now() + '-' + filename;
  let uploadPath = uploadDir + '/' + filename;

  fsExtra.moveSync(tmpUploadPath, uploadPath);

  appendixService.process(taskId, tags, fileSize, contentType, filename, uploadPath).then((result) => {
    response(res, false, ['Pomyślnie załadowano załącznik.'], result.resources.resources[0]);
  });
fork icon0
star icon0
watch icon1

+ 3 other calls in file

356
357
358
359
360
361
362
363
364
365
366
function finalizeBin(outputName, outputFolder, tempProjDir) {
    // move compiled model to destination
    console.info('Done compiling. Moving to output folder...')
    const src = path.join(tempProjDir, 'deploy', `${wlProjectName}.bin`);
    const dst = path.join(outputFolder, outputName);
    fs.moveSync(src, dst, { overwrite: true });


    // remove temporary folder
    removeTmpDir();
}
fork icon0
star icon0
watch icon1

+ 14 other calls in file

742
743
744
745
746
747
748
749
750
751

files.forEach((file) => {
  if (typeof file === 'string') {
    fse.moveSync(`${tempPath}/${file}`, `${root}/${file}`, {});
  } else {
    fse.moveSync(`${tempPath}/${file[0]}`, `${root}/${file[1]}`, {});
  }
});

fse.ensureDirSync(`${root}/microservices`, {});
fork icon0
star icon0
watch icon1

+ 5 other calls in file

146
147
148
149
150
151
152
153
154
155
156
        logfile.info('Download complete files uploaded:');
        const syncedLogsDir = `${configData.m1mtfDir}/logs/syncedlogs`;
        mkdirp.sync(syncedLogsDir);
        matches.forEach((item) => {
            logfile.info(path.basename(item));
            fs.moveSync(item, path.join(`${syncedLogsDir}`, path.basename(item)));
        });
    });


program.command('backupdb')
fork icon0
star icon0
watch icon1

+ 23 other calls in file

168
169
170
171
172
173
174
175
176
177
  if(fs.existsSync(path.join(bePath, './mapper'))) {
    // 存在mapper
    fs.copySync(path.join(bePath, './mapper'), path.join(process.cwd(), `./src/resource`))
  }
  // 移动依赖
  fs.moveSync(path.join(tempFolder, `./node_modules`), path.join(destAppDir, `./node_modules`), {overwrite: true})
}
if(fs.existsSync(fePath)) { // 存在前端
  if(pkg?.mybricks?.type !== 'system') { // 非系统任务
    const srcHomePage = path.join(fePath, './index.html') // 约定
fork icon0
star icon0
watch icon1

+ 4 other calls in file

1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
// console.log(curFile);
let series_path_str = curFile.substring(curFile.lastIndexOf('/')+1);
// console.log(series_descriptionArr[series_pathArr.indexOf(series_path_str)]);
// console.log(modalityArr[series_pathArr.indexOf(series_path_str)]);
// console.log(series_descriptionArr[series_pathArr.indexOf(series_path_str)]+' '+modalityArr[series_pathArr.indexOf(series_path_str)]);
fs.moveSync(curFile,curFile + ' '+ series_descriptionArr[series_pathArr.indexOf(series_path_str)]+' '+modalityArr[series_pathArr.indexOf(series_path_str)], function (err) {
    if (err) throw err;
});
total+=1;
// console.log(files.length)
fork icon0
star icon0
watch icon3

+ 34 other calls in file

190
191
192
193
194
195
196
197
198
199
publicPath = './public/proyectos/' + idProyecto;

try {
    // Primero revisar si existe caducadosPath
    if (fs.existsSync(caducadosPath)) {
        fs.moveSync(caducadosPath, publicPath);
        console.log("¡Carpetas movidas correctamente! desde: " + caducadosPath + " a: " + publicPath);
        
        // Ahora visibiliza todo
        Proyecto.visibilizar(req.params.idproyecto, req.params.idcliente, req.mysql, (__error, data) => {
fork icon0
star icon0
watch icon1

319
320
321
322
323
324
325
326
327
  // console.log('File download failed:' + url);
  return callback(new Error('File download failed. Unknown error.'));
}

if (utils.fileExists(output_file_tmp)) {
  fse.moveSync(output_file_tmp, local_file, {overwrite: true});
}

var result_file = local_file;
fork icon0
star icon0
watch icon0

function icon

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