fs.renameSync()方法用於將給定舊路徑下的文件同步重命名為給定新路徑。如果目標文件已經存在,它將覆蓋目標文件。
用法:
fs.renameSync( oldPath, newPath )
屬性值:
- oldPath:它包含必須重命名的文件的路徑。它可以是字符串,緩衝區或URL。
- newPath:它包含必須將文件重命名為的新路徑。它可以是字符串,緩衝區或URL。
以下示例說明了Node.js中的fs.renameSync()方法:
範例1:本示例使用fs.renameSync()方法重命名文件。
// Node.js program to demonstrate the
// fs.renameSync() method
// Import the filesystem module
const fs = require('fs');
// List all the filenames before renaming
getCurrentFilenames();
// Rename the file
fs.renameSync('hello.txt', 'world.txt');
// List all the filenames after renaming
getCurrentFilenames();
// function to get current filenames in directory
function getCurrentFilenames() {
console.log("Current filenames:");
fs.readdirSync(__dirname).forEach(file => {
console.log(file);
});
}
輸出:
Current filenames: hello.txt index.js package.json Current filenames: index.js package.json world.txt
範例2:本示例使用fs.renameSync()方法演示文件重命名過程中的錯誤。
// Node.js program to demonstrate the
// fs.renameSync() method
// Import the filesystem module
const fs = require('fs');
// List all the filenames before renaming
getCurrentFilenames();
// Rename a non-existent file
fs.renameSync('nonexist.txt', 'world.txt');
// List all the filenames after renaming
getCurrentFilenames();
// Function to get current filenames in directory
function getCurrentFilenames() {
console.log("Current filenames:");
fs.readdirSync(__dirname).forEach(file => {
console.log(file);
});
}
輸出:
Current filenames: index.js package.json world.txt internal/fs/utils.js:220 throw err; ^ Error:ENOENT:no such file or directory, rename 'nonexist.txt' -> 'world.txt' at Object.renameSync (fs.js:643:3) at Object. (G:\tutorials\nodejs-fs-renameSync\index.js:29:4) at Module._compile (internal/modules/cjs/loader.js:956:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:973:10) at Module.load (internal/modules/cjs/loader.js:812:32) at Function.Module._load (internal/modules/cjs/loader.js:724:14) at Function.Module.runMain (internal/modules/cjs/loader.js:1025:10) at internal/main/run_main_module.js:17:11 { errno:-4058, syscall:'rename', code:'ENOENT', path:'nonexist.txt', dest:'world.txt' }
參考: https://nodejs.org/api/fs.html#fs_fs_renamesync_oldpath_newpath
相關用法
注:本文由純淨天空篩選整理自sayantanm19大神的英文原創作品 Node.js | fs.renameSync() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。