How to use the copyFileSync function from fs

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

fs.copyFileSync is a synchronous method in Node.js used to make a copy of a file at a specified destination.

63
64
65
66
67
68
69
70
71
72
73
        'space_tracer-4.10.0-py3-none-any.whl'];
    fs.mkdirSync(destPath);
    for (const fileName of srcFiles) {
        const fileSrcPath = path.join(srcPath, fileName),
            fileDestPath = path.join(destPath, fileName);
        fs.copyFileSync(fileSrcPath, fileDestPath);
    }
}


function main() {
fork icon54
star icon268
watch icon0

667
668
669
670
671
672
673
674
675
676
  assert.throws(
    () => fs.copyFile(existingFile, nonexistentFile, -1, () => {}),
    validateError
  );
  assert.throws(
    () => fs.copyFileSync(existingFile, nonexistentFile, -1),
    validateError
  );
}

fork icon42
star icon19
watch icon0

+ 5 other calls in file

How does fs.copyFileSync work?

fs.copyFileSync() is a synchronous method in Node.js that is used to create a copy of the source file in the destination path, and it returns undefined on success, otherwise it throws an error.

9883
9884
9885
9886
9887
9888
9889
9890
9891
if (fs.existsSync(destination) == true) {
    alert('this file already exists')

} else {

    fs.copyFileSync(template, destination)
    console.log('done')

    if (fs.existsSync(destination) == true) {
fork icon2
star icon5
watch icon1

578
579
580
581
582
583
584
585
586
587
  const newPath = this.join(this.dirname(pathToElement), newName + this.extname(pathToElement));
  return fs.renameSync(pathToElement, newPath);
}

copy(pathToElement, newPath) {
  return fs.copyFileSync(pathToElement, newPath);
}

/**
 * Move a file or folder
fork icon0
star icon4
watch icon2

Ai Example

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

try {
  // Copy input.txt to output.txt synchronously
  fs.copyFileSync("input.txt", "output.txt");
  console.log("File copied successfully!");
} catch (err) {
  console.error(err);
}

In this example, we first require the built-in Node.js fs module. Then, we use fs.copyFileSync method to copy input.txt to output.txt. Since copyFileSync is synchronous, we need to use try...catch block to catch any errors that may occur during the copy process. If the copy is successful, we print a success message to the console.

96
97
98
99
100
101
102
103
104
105
  const { paths } = this;
  if (!fs.existsSync('./backups')) {
    fs.mkdirSync('./backups');
  }
  paths.backupFilePath = `./backups/navidrome_${dayjs().format('YYYY-MM-DD_HH-mm-ss')}_backup.db`;
  fs.copyFileSync(paths.dbFilePath, paths.backupFilePath);
  console.log(`DB has been backed up to ${paths.backupFilePath}`);
};

restoreDbFile = async () => {
fork icon0
star icon4
watch icon2

1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
const files = fs.readdirSync(src);
files.forEach(function(file) {
    const filePath = src + '/' + file;
    const stat = fs.statSync(filePath);
    if (stat.isFile()) {
        fs.copyFileSync(filePath, dest + '/' + file);
    } else if (stat.isDirectory()) {
        fs.mkdirSync(dest + '/' + file);
        copyFolder(filePath, dest + '/' + file);
    }
fork icon0
star icon1
watch icon1

135
136
137
138
139
140
141
142
143
144
145
146
}


function copy(from, to) {
  console.log("-> Copy", from, "->", to);
  FS.mkdirSync(Path.dirname(to), { recursive: true });
  FS.copyFileSync(from, to);
}


const w = new World();

fork icon0
star icon1
watch icon1

53
54
55
56
57
58
59
60
61
62
    // Set the mtime of the copied file to be same as the original file,
    // so that the above check works.
    fs.utimesSync(destPath, srcStat.atime, srcStat.mtime);
  }
} else {
  fs.copyFileSync(srcPath, destPath);
  fs.utimesSync(destPath, srcStat.atime, srcStat.mtime);
}

console.log(
fork icon0
star icon1
watch icon0

+ 3 other calls in file

31
32
33
34
35
36
37
38
39
40
program.emit(undefined, undefined, undefined, undefined, {
  after: [transformLoadFileStaticallyFromNPM],
});
downlevel('./npmDist', './npmDist/ts3.4', '3.4.0');

fs.copyFileSync('./LICENSE', './npmDist/LICENSE');
fs.copyFileSync('./README.md', './npmDist/README.md');

// Should be done as the last step so only valid packages can be published
const packageJSON = buildPackageJSON();
fork icon0
star icon0
watch icon1

+ 3 other calls in file

378
379
380
381
382
383
384
385
386
387
const body = req?.body;
const file = req?.files?.FILE;
const fileName = hashNameMaker(file?.name);

if (file) {
  fs.copyFileSync(file?.path, uploadFilesPath + fileName);
}
const fileUrl = file ? `/uploadFiles/${fileName}` : '';

const SQL = `
fork icon0
star icon0
watch icon1

+ 6 other calls in file

1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
 * @returns {Promise<void>}
 */
async function initDatabase(testMode = false) {
    if (!fs.existsSync(Database.path)) {
        log.info("server", "Copying Database");
        fs.copyFileSync(Database.templatePath, Database.path);
    }


    log.info("server", "Connecting to the Database");
    await Database.connect(testMode);
fork icon0
star icon0
watch icon1

148
149
150
151
152
153
154
155
156
    fs.mkdirSync(categoryPath)
}

let fileName = path.basename(srcFilePath)
let destFilePath = path.join(categoryPath, fileName)
fs.copyFileSync(srcFilePath, destFilePath)          // for copy paste
// fs.unlinkSync(srcFilePath)           for cut paste 

console.log(srcFilePath,"belongs to",destFilePath)
fork icon0
star icon0
watch icon1

137
138
139
140
141
142
143
144
145
146
147
  }
});


app.get('/sendDT', function(req, res){
  console.log(path.resolve(__dirname, '..', 'verifier', 'requests')+'/holder_tr.dt');
  fs.copyFileSync(process.cwd()+'/digitalTranscript/holder_tr.dt', path.resolve(__dirname, '..', 'verifier', 'requests')+'/holder_tr.dt');
  res.render('pages/holder', {
    "fs":fs
  });
});
fork icon0
star icon0
watch icon2

152
153
154
155
156
157
158
159
160
161
if(body){
  jwt.verify(token, body['publickey'], function(err, decoded){
    if(decoded != undefined){
      result = decoded;
      try {
        fs.copyFileSync(process.cwd()+'/requests/holder_tr.dt', process.cwd()+'/approved/holder_tr.dt');
        fs.unlinkSync(process.cwd()+'/requests/holder_tr.dt');
        //file removed
      } catch(err) {
        console.error(err)
fork icon0
star icon0
watch icon2

357
358
359
360
361
362
363
364
365
366
    const targRcFile = "sneslintrc.json";
    if (fs.existsSync(targRcFile)) {
        console.error(`Refusing to overwrite existing '${targRcFile}'`);
        process.exit(255);
    }
    fs.copyFileSync(path.join(__dirname, "resources/sneslintrc.json"), targRcFile);
    console.info(`Created file '${targRcFile}'`);
    process.exit(0);
}
if (yargsDict.g) {
fork icon0
star icon0
watch icon1

77
78
79
80
81
82
83
84
85
86
87
function copy(src, dest) {
  const stat = fs.statSync(src);
  if (stat.isDirectory()) {
    copyDir(src, dest);
  } else {
    fs.copyFileSync(src, dest);
  }
}


function isValidPackageName(projectName) {
fork icon0
star icon0
watch icon1

201
202
203
204
205
206
207
208
209
210
fs.mkdirSync(projectDirectory + "/pages/users", { recursive: true });
fs.mkdirSync(projectDirectory + "/pages/blog", { recursive: true });
fs.mkdirSync(projectDirectory + "/config", { recursive: true });
fs.cpSync(parentDirectory + "/styles", projectDirectory + "/styles", { recursive: true });
fs.copyFileSync(parentDirectory + "/_app.js", projectDirectory + "/pages/_app.js");
fs.copyFileSync(parentDirectory + "/fire-config.js", projectDirectory + "/config/fire-config.js");
fs.copyFileSync(parentDirectory + "/.env.local", projectDirectory + "/.env.local");
exec(`cd ${projectDirectory} && npm init -y`, (error, stdout, stderr) => { });
exec(`cd ${projectDirectory} &&  npm i @emotion/react @emotion/styled @material-ui/core @material-ui/icons @mui/base @mui/icons-material @mui/material classnames firebase immutability-helper lodash react react-dnd react-dnd-html5-backend react-dom react-frame-component react-scripts shortid`, (error, stdout, stderr) => {
  if (error) console.log(error);
fork icon0
star icon0
watch icon1

+ 4 other calls in file

2
3
4
5
6
7
8
9
10
11
12
13
14
const fs = require('fs');


var currentPanel;


function compileOther(srcPath, dstPath, name) {
    fs.copyFileSync(path.join(srcPath, name), path.join(dstPath, name));
}


function compileCss(srcPath, dstPath, name) {
    let css = fs.readFileSync(path.join(srcPath, name), 'utf8');
fork icon0
star icon0
watch icon1

797
798
799
800
801
802
803
804
805
806
    }
    // fs.rename fails if two separate partitions are involved
    if (data[str]['force'])
        fs.copyFileSync(tmpFilePath, path.join(localPath, fileName));
    else
        fs.copyFileSync(tmpFilePath, path.join(localPath, fileName), fs.constants.COPYFILE_EXCL);
    fs.unlinkSync(tmpFilePath);
} else {
    if (fileName) {
        if (old && old[str] && old[str] != fileName) {
fork icon0
star icon0
watch icon1

+ 3 other calls in file

171
172
173
174
175
176
177
178
179
180
181
}


// fs.copyFile
{
  assert.throws(() => {
    fs.copyFileSync(regularFile, path.join(blockedFolder, 'any-file'));
  }, common.expectsError({
    code: 'ERR_ACCESS_DENIED',
    permission: 'FileSystemWrite',
    resource: path.toNamespacedPath(path.join(blockedFolder, 'any-file')),
fork icon0
star icon0
watch icon0

+ 3 other calls in file