发布时间:2025-12-09 11:44:48 浏览次数:1
fs.copyFile()方法用于将文件从源路径异步复制到目标路径。默认情况下,Node.js将覆盖文件(如果文件已存在于给定的目的地)。可选的mode参数可用于修改复制操作的行为。
用法:
fs.copyFile( src, dest, mode, callback )
参数:该方法接受上述和以下描述的三个参数:
这些常量也可以与按位或组合以创建多个值的掩码。它是一个可选参数。该参数的默认值为0。
以下示例说明了Node.js中的fs.copyFile()方法:
范例1:本示例显示了“example_file.txt”文件到“copied_file.txt”文件的复制操作。
// Node.js program to demonstrate the // fs.copyFile() method // Import the filesystem module const fs = require('fs'); // Get the current filenames // before the function getCurrentFilenames(); console.log("\nFile Contents of example_file:", fs.readFileSync("example_file.txt", "utf8")); // Copying the file to a the same name fs.copyFile("example_file.txt", "copied_file.txt", (err) => { if (err) { console.log("Error Found:", err); } else { // Get the current filenames // after the function getCurrentFilenames(); console.log("\nFile Contents of copied_file:", fs.readFileSync("copied_file.txt", "utf8")); } }); // Function to get current filenames // in directory function getCurrentFilenames() { console.log("\nCurrent filenames:"); fs.readdirSync(__dirname).forEach(file => { console.log(file); }); }输出:
Current filenames:example_file.txtindex.jsFile Contents of example_file:This is a test file.Current filenames:copied_file.txtexample_file.txtindex.jsFile Contents of copied_file:This is a test file.
范例2:本示例说明了目标已存在时复制操作失败。
// Node.js program to demonstrate the // fs.copyFile() method // Import the filesystem module const fs = require('fs'); // Get the current filenames // before the function getCurrentFilenames(); console.log("\nFile Contents of example_file:", fs.readFileSync("example_file.txt", "utf8")); // Copying the file to a the same name fs.copyFile("example_file.txt", "copied_file.txt", fs.constants.COPYFILE_EXCL, (err) => { if (err) { console.log("Error Found:", err); } else { // Get the current filenames // after the function getCurrentFilenames(); console.log("\nFile Contents of copied_file:", fs.readFileSync("copied_file.txt", "utf8")); } }); // Function to get current filenames // in directory function getCurrentFilenames() { console.log("\nCurrent filenames:"); fs.readdirSync(__dirname).forEach(file => { console.log(file); }); }输出:
Current filenames:copied_file.txtexample_file.txtindex.jsFile Contents of example_file:This is a test file.Error:[Error:EEXIST:file already exists, copyfile 'G:\tutorials\nodejs-fs-copyFile\example_file.txt' -> 'G:\tutorials\nodejs-fs-copyFile\copied_file.txt'] { errno:-4075, code:'EEXIST', syscall:'copyfile', path:'G:\\tutorials\\nodejs-fs-copyFile\\example_file.txt', dest:'G:\\tutorials\\nodejs-fs-copyFile\\copied_file.txt'}参考: https://nodejs.org/api/fs.html#fs_fs_copyfile_src_dest_mode_callback