首页 > 解决方案 > 在nodejs中,如果文件包含指定的文本,如何读取文件并将其移动到另一个文件夹

问题描述

所以我有以下代码

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 是由单独的线程执行的,所以“已处理”的值不可靠。

我对nodejs不是很熟悉,所以任何帮助都将不胜感激。

标签: node.js

解决方案


是的,你是对的,你的执行是由不同的线程执行的。

在这种情况下,您需要使用 Promise。

您可以使用“ 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

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

希望它可以帮助你。

问候


推荐阅读