Node.js 在nodejs中,如果文件包含指定的文本,如何读取文件并将其移动到另一个文件夹

Node.js 在nodejs中,如果文件包含指定的文本,如何读取文件并将其移动到另一个文件夹,node.js,Node.js,所以我有以下代码 var processed; fs.readFile(path, 'utf-8', function(err, data) { processed = false; //checking if text is in file and setting flag processed = true; }); if (processed == true) { try { var fname = path.substring(path.l

所以我有以下代码

var processed;
fs.readFile(path, 'utf-8', function(err, data) {
    processed = false;
    //checking if text is in file and setting flag
    processed = true;
});

if (processed == true) {
    try {
        var fname = path.substring(path.lastIndexOf("\\") + 1);
        fs.moveSync(path, './processedxml/' + fname, {
            overwrite: true
        })
    } catch (err) {
        console.log("Error while moving file to processed folder " + err);
    }

}
但是我没有得到想要的输出。因为readfile看起来是由单独的线程执行的,所以“processed”的值不可靠


我对nodejs不太熟悉,因此非常感谢您的帮助。

是的,您是对的,您的执行是由不同的线程执行的

在这个场景中,您需要使用承诺

您可以通过使用“Promise FS”轻松解决您的需求(您也可以使用任何其他Promise解决方案)

您的代码如下所示:

fs = require('promise-fs');

var fname = 'test.txt' ;
var toMove = false ;

fs.readFile('test.txt','utf8')
    .then (function (content) {
        if(content.indexOf('is VALID') !== -1) {
            console.log('pattern found!');
            toMove = true ;
        }
        else { toMove = false
        }
        return toMove ;
    }).
    then (function (toMove) {
           if(toMove) {
              var oldPath = 'test.txt'
              var newPath = '/tmp/moved/file.txt'
              fs.rename(oldPath, newPath, function (err) {
                if (err) throw err
                console.log('Successfully renamed - moved!')
              }) ;
           }
    })
    .catch (function (err) {
        console.log(err);
    })
创建文件“test.txt”并添加以下内容:

this is text.file contents
token is VALID
上面的代码将评估“是有效的”是否作为内容存在,如果是,则将文件“test.txt”从当前文件夹移动到“/tmp”目录中名为“moved”的新文件夹。它还将文件重命名为“file.txt”文件名

希望对你有帮助


关于

看起来您正在跟踪路径,试图将其用作变量和节点模块。最简单的方法是为文件选择不同的变量名,并将处理逻辑移到
fs.readFile
的回调中

var path = require('path');
var fs = require('fs-extra');

var file = 'some/file/path/foo.xml';
var text = 'search text';

fs.readFile(file, 'utf-8', function (err, data) {
    if (err) {
        console.error(err);
    } else {
        //checking if text is in file and setting flag
        if (data.indexOf(text) > -1) {
            try {
                var fname = path.basename(file);
                fs.moveSync(file, './processedxml/' + fname, {
                    overwrite: true
                })
            } catch (err) {
                console.log("Error while moving file to processed folder " + err);
            }
        }
    }
});

还有一个同步版本可能是重复的:
fs.readFileSync(路径,选项)
只需将代码移动到函数中,而不是设置标志。@Jake在读取同一文件时不能移动它
fs.readFile
回调在读取文件后调用,而不是在打开文件时调用,可能还有另一个问题,可能您正试图将文件移动到不存在的文件夹中。