How to use the cpSync function from fs

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

fs.cpSync is a method in Node.js that synchronously copies a file or directory from one location to another.

42
43
44
45
46
47
48
49
50
51
52
  }
}


function copyChangedFiles(packageName, sourceDir, targetDir) {
  console.log(`[${new Date().toLocaleTimeString()}] Updating ${packageName}`);
  fs.cpSync(sourceDir, targetDir, {
    recursive: true,
    filter: (source, dest) => {
      if (!fs.existsSync(dest)) {
        return true;
fork icon24
star icon13
watch icon0

563
564
565
566
567
568
569
570
571
572
573
574
575
}


async function copyRepository() {
    const source = `${process.cwd()}/resources/${context.directory}`;


    cpSync(source, context.repositoryPath, {recursive: true})
}


function repository(projectName = "repository.git") {
    return {
fork icon1
star icon8
watch icon2

How does fs.cpSync work?

fs.cpSync is a function in Node.js that is used to copy a file or a directory from a source location to a destination location synchronously. The function takes two arguments: the source file or directory path and the destination path. If the source is a directory, the destination must also be a directory. The function creates a new file or directory at the destination path with the same content as the source file or directory, and it returns undefined if the operation is successful. Otherwise, it throws an error with the relevant error message.

19
20
21
22
23
24
25
26
27
28
29
30


const downloader = (/** @type {string} */ root) => {
  const submodule = 'obsidian';
  for (const fileOrFolder of readdirSync(submodule)) {
    if (!fileOrFolder.startsWith('.')) {
      cpSync(join(submodule, fileOrFolder), join(root, fileOrFolder.split('-').slice(-1).join('').trim()), { recursive: true });
    }
  }


  for (const file of walkSync(root, { globs: [`**/*.md`, `**/*.mdx`]})) {
fork icon0
star icon1
watch icon0

362
363
364
365
366
367
368
369
370
371
    fs.copyFileSync(path.join(__dirname, "resources/sneslintrc.json"), targRcFile);
    console.info(`Created file '${targRcFile}'`);
    process.exit(0);
}
if (yargsDict.g) {
    fs.cpSync(path.join(__dirname, "resources/snglobals"), "snglobals", {
        preserveTimestamps: true,
        recursive: true,
        force: true,
    });
fork icon0
star icon0
watch icon1

Ai Example

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

try {
  fs.copyFileSync("path/to/source/file", "path/to/destination/file");
  console.log("File copied successfully.");
} catch (err) {
  console.error("Error while copying file:", err);
}

In this example, fs.copyFileSync is used to copy the file from the source path to the destination path synchronously. If the copy is successful, a message is logged to the console. If an error occurs, an error message is logged to the console.

199
200
201
202
203
204
205
206
207
208
fs.mkdirSync(projectDirectory, { recursive: true });
fs.mkdirSync(projectDirectory + "/components", { recursive: true });
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) => { });
fork icon0
star icon0
watch icon1

25
26
27
28
29
30
31
32
33
34
  hooks: {
    postPackage: async (forgeConfig, options) => {
      console.log('Packages built at:', options.outputPaths);
      const outputPath = options.outputPaths[0];


      fs.cpSync(outputPath, path.resolve(__dirname, '../client'), { recursive: true });
    }
  }
};
fork icon0
star icon0
watch icon0

83
84
85
86
87
88
89
90
91
92

// A common approach to building a starter template is to
// create a `template` folder which will house the template
// and the files we want to create.
const templateDir = path.resolve(__dirname, '../project_template');
fs.cpSync(templateDir, projectDir, { recursive: true });

// Get executable path
let binaryFileName = "";
switch (os.platform()) {
fork icon0
star icon0
watch icon0

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


// fs.cp
{
  assert.throws(() => {
    fs.cpSync(blockedFile, path.join(blockedFolder, 'any-other-file'));
  }, common.expectsError({
    code: 'ERR_ACCESS_DENIED',
    permission: 'FileSystemRead',
    // cpSync calls statSync before reading blockedFile
fork icon0
star icon0
watch icon0

+ 3 other calls in file

189
190
191
192
193
194
195
196
197
198
199
}


// fs.cp
{
  assert.throws(() => {
    fs.cpSync(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