我正在try 循环并获取目录中的文件,但在实现它时遇到了一些困难.如何拉入多个文件,然后将它们移动到另一个文件夹?

var dirname = 'C:/FolderwithFiles';
console.log("Going to get file info!");
fs.stat(dirname, function (err, stats) {
    if (err) {
        return console.error(err);
    }
    console.log(stats);
    console.log("Got file info successfully!");

    // Check file type
    console.log("isFile ? " + stats.isFile());
    console.log("isDirectory ? " + stats.isDirectory());
});

推荐答案

用回调来回答问题

您希望使用fs.readdir函数获取目录内容,使用fs.rename函数实际进行重命名.如果您需要等待这两个函数完成后再运行代码,那么这两个函数都有同步版本.

我写了一个很快的脚本,按照你的描述.

var fs = require('fs');
var path = require('path');
// In newer Node.js versions where process is already global this isn't necessary.
var process = require("process");

var moveFrom = "/home/mike/dev/node/sonar/moveme";
var moveTo = "/home/mike/dev/node/sonar/tome"

// Loop through all the files in the temp directory
fs.readdir(moveFrom, function (err, files) {
  if (err) {
    console.error("Could not list the directory.", err);
    process.exit(1);
  }

  files.forEach(function (file, index) {
    // Make one pass and make the file complete
    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'.

更新:财政司司长.promise 使用异步/等待功能

受ma11hew28答案(shown here)的启发,这里的内容与上面相同,但fs.promises中的异步函数.正如ma11hew28所指出的,与v12中添加的fs.promises.opendir相比,这可能有内存限制.12.0.

下面是快速代码.

//jshint esversion:8
//jshint node:true
const fs = require( 'fs' );
const path = require( 'path' );

const moveFrom = "/tmp/movefrom";
const moveTo = "/tmp/moveto";

// Make an async function that gets executed immediately
(async ()=>{
    // Our starting point
    try {
        // Get the files as an array
        const files = await fs.promises.readdir( moveFrom );

        // Loop them all with the new for...of
        for( const file of files ) {
            // Get the full paths
            const fromPath = path.join( moveFrom, file );
            const toPath = path.join( moveTo, file );

            // Stat the file to see if we have a file or dir
            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 );

            // Now move async
            await fs.promises.rename( fromPath, toPath );

            // Log because we're crazy
            console.log( "Moved '%s'->'%s'", fromPath, toPath );
        } // End for...of
    }
    catch( e ) {
        // Catch anything bad that happens
        console.error( "We've thrown! Whoops!", e );
    }

})(); // Wrap in parenthesis and call now

Node.js相关问答推荐

Twilio-获取呼叫录音不起作用的请求

聚合发布/订阅消息

如何将我的Redis客户端配置为在禁用群集模式的情况下使用读取副本?

Node.js分页返回空数组

在函数上执行 toString 的Typescript 会产生奇怪的字符 (path_1, (0, Promise.writeFile))

我如何在 Raku 的供应中注册不同的事件?

MongoDB - mongoose :如何查询这个? 填充()不起作用.它显示空

为什么它无法发送发布请求并更改为 chrome 中的获取方法?

Node.js 上的 CLI 应用程序如何通过 child_process 将选项值作为参数传递给 Shell 命令

为什么我的 Cypress Post 请求的请求正文是空的?

如何使用 node 在 koa.js 中发送响应

将 AllowDiskUse true 添加到 node.js 中的 MongoDB 聚合?

无法更新MongoDB中的文档:";伯森场';writeConcern.w';是错误的类型';数组'&引用;

file.slim.js 中的苗条是什么

如何使用 UglifyJS 缩小文件夹中的多个 Javascript 文件?

在 PassportJS 中使用多种本地策略

带有加密的nodejs中的SALT和HASH密码

Node.js -Firebase 服务帐户私钥不会解析

node.js 示例

webpack-dev-server 找不到模块webpack