使用回调函数的旧答案
您想使用fs.readdir函数获取目录内容,使用fs.rename函数进行重命名。如果需要在运行后续代码之前等待它们完成,则这两个函数都有同步版本。
我编写了一个快速脚本来执行您所描述的操作。
var fs = require('fs');
var path = require('path');
var process = require("process");
var moveFrom = "/home/mike/dev/node/sonar/moveme";
var moveTo = "/home/mike/dev/node/sonar/tome"
fs.readdir(moveFrom, function (err, files) {
if (err) {
console.error("Could not list the directory.", err);
process.exit(1);
}
files.forEach(function (file, index) {
var fromPath = path.join(moveFrom, file);
var toPath = path.join(moveTo, file);
fs.stat(fromPath, function (error, stat) {
if (error) {
console.error("Error stating file.", error);
return;
}
if (stat.isFile())
console.log("'%s' is a file.", fromPath);
else if (stat.isDirectory())
console.log("'%s' is a directory.", fromPath);
fs.rename(fromPath, toPath, function (error) {
if (error) {
console.error("File moving error.", error);
} else {
console.log("Moved file '%s' to '%s'.", fromPath, toPath);
}
});
});
});
});
我在本地机器上进行了测试。
node testme.js
'/home/mike/dev/node/sonar/moveme/hello' is a file.
'/home/mike/dev/node/sonar/moveme/test' is a directory.
'/home/mike/dev/node/sonar/moveme/test2' is a directory.
'/home/mike/dev/node/sonar/moveme/test23' is a directory.
'/home/mike/dev/node/sonar/moveme/test234' is a directory.
Moved file '/home/mike/dev/node/sonar/moveme/hello' to '/home/mike/dev/node/sonar/tome/hello'.
Moved file '/home/mike/dev/node/sonar/moveme/test' to '/home/mike/dev/node/sonar/tome/test'.
Moved file '/home/mike/dev/node/sonar/moveme/test2' to '/home/mike/dev/node/sonar/tome/test2'.
Moved file '/home/mike/dev/node/sonar/moveme/test23' to '/home/mike/dev/node/sonar/tome/test23'.
Moved file '/home/mike/dev/node/sonar/moveme/test234' to '/home/mike/dev/node/sonar/tome/test234'.
更新:使用async/await的fs.promises函数
受ma11hew28答案的启发(在此处显示),这里与上面相同,但使用fs.promises中的异步函数。正如ma11hew28所指出的那样,这可能存在内存限制,相对于在v12.12.0中添加的fs.promises.opendir。
以下是快速代码。
const fs = require( 'fs' );
const path = require( 'path' );
const moveFrom = "/tmp/movefrom";
const moveTo = "/tmp/moveto";
(async ()=>{
try {
const files = await fs.promises.readdir( moveFrom );
for( const file of files ) {
const fromPath = path.join( moveFrom, file );
const toPath = path.join( moveTo, file );
const stat = await fs.promises.stat( fromPath );
if( stat.isFile() )
console.log( "'%s' is a file.", fromPath );
else if( stat.isDirectory() )
console.log( "'%s' is a directory.", fromPath );
await fs.promises.rename( fromPath, toPath );
console.log( "Moved '%s'->'%s'", fromPath, toPath );
}
}
catch( e ) {
console.error( "We've thrown! Whoops!", e );
}
})();