1

我在尝试着,

  1. 持续监视目录中的文件,
  2. 如果有任何文件进入,根据文件类型(从文件名推断),调用 GET api 获取 ID/密钥
  3. 使用另一个 API 中的密钥发布数据。
  4. 将发布数据的文件移动到另一个目录

我用过 Chokidar,请求承诺包。

问题是,只要在目录中粘贴了多个文件,就会快速调用 API,这样即使在提交第一个文件的数据之前,第二个文件也会被处理。这会导致从第一个 API 获取 ID 的问题。这两个文件现在都将具有相同的 Key/ID。请告诉我,如何解决这个问题,以便我们从每个文件中获取唯一的数据 ID。

这是我的代码:

var chokidar = require('chokidar');
const fs = require('fs');
var rp = require('request-promise');
var globalpath = require('path');
console.log("path", globalpath.resolve(process.cwd(), './Data'));

var watcher = chokidar.watch(globalpath.resolve(process.cwd(), './Data/*.json'), {

    ignored: /^\./,
    persistent: true
});
watcher
    .on('add', function (path) {
        readfile(path);
    });

async function readfile(path) {
    fs.readFile(path, function (err, data) {
        if (err != null) {
            console.log(err);
        }
        var loadingdata = JSON.parse(data);
        if (path.indexOf("PO") > -1) {
            var options = {
                method: 'GET',
                uri: 'http://localhost:3005/GetNewPOKey',
                json: true
            };

            rp(options)
                .then(function (parsedBody) {
                    console.log(parsedBody.NextPOKey);
                    var options2 = {
                        method: 'POST',
                        uri: 'http://localhost:3005/createPO?id='+parsedBody.NextPOKey,
                        body: loadingdata,
                        json: true
                    };

                    rp(options2)
                        .then(function (parsedBody) {
                            console.log(parsedBody);
                            if (parsedBody === "OK") {
                                moveit(path);
                            }
                            // POST succeeded...
                        })
                        .catch(function (err) {
                            console.log("API error :" + err);
                            // POST failed...
                        });
                    // GET succeeded...
                })
                .catch(function (err) {
                    console.log("API error :" + err);
                    // GET failed...
                });

        }
        else {
            console.log("Unknown File" + path);
        }

    });

}

function moveit(mypath) {
    // console.log("This file is posted " + path);
    let oldpath = mypath;
    let newpath = globalpath.resolve(process.cwd(), './History') + "/" + globalpath.basename(mypath.split('.').join('-' + Date.now() + '.'));
    console.log("This is the new filename " + newpath);
    fs.rename(oldpath, newpath, (err) => {
        if (err) throw err;
        console.log('Rename complete!');
    });
}
4

1 回答 1

0

我找不到合适的解决方案来继续使用 Chokidar 的观察器。相反,我编写了这段代码并在操作系统中安排了脚本,以监视文件。

const fs = require('fs');
var request = require('request');
var rp = require('request-promise');
var globalpath = require('path');
console.log("path", globalpath.resolve(process.cwd(), './Data'));
const directoryPath = globalpath.resolve(process.cwd(), './Data');

fs.readdir(directoryPath, async function (err, files) {
    if (err) {
        return console.log('Unable to scan directory: ' + err);
    }
    let allfiledata = [];
    let allkeys = [];

    files.forEach(function (file) {
        if (file.indexOf("json") > -1) {
            console.log(file);
            data = fs.readFileSync(directoryPath + "/" + file)
            var loadingdata = JSON.parse(data);
            allfiledata.push(loadingdata);
            moveit(directoryPath + "/" + file);
        }
    });
    if (allfiledata.length > 0) {
        request({
            url: 'http://localhost:3005/GetNewPOKey',
            json: true
        }, function (err, res, body) {
            if (err) {
                console.log("API error :" + err);
            }
            let nextkey = body.NextPOKey;
            allkeys.push(nextkey);
            var number = parseInt(nextkey.slice(2, ));
            for (let i = 1; i < allfiledata.length; i++) {
                number = number + 1;
                allkeys.push("PO" + number);
            }
            console.log(allkeys);
            console.log(allfiledata.length);
            for (let i = 0; i < allkeys.length; i++) {
                //setTimeout(function(){console.log(Date.now())},120000);
                console.log(allfiledata[i]);
                console.log('http://localhost:3005/createPO?id=' + allkeys[i]);
                var options2 = {
                    method: 'POST',
                    uri: 'http://localhost:3005/createPO?id=' + allkeys[i],
                    body: allfiledata[i],
                    json: true
                };

                rp(options2)
                    .then(function (parsedBody) {
                        console.log(parsedBody);
                        if (parsedBody === "OK") {
                            console.log("success");
                        }
                        // POST succeeded...
                    })
                    .catch(function (err) {
                        console.log("API error :" + err);
                        // POST failed...
                    });
            }
        });
    }
});


function moveit(mypath) {
    let oldpath = mypath;
    let newpath = globalpath.resolve(process.cwd(), './History') + "/" + globalpath.basename(mypath.split('.').join('-' + Date.now() + '.'));
    console.log("This is the new filename " + newpath);
    fs.rename(oldpath, newpath, (err) => {
        if (err) throw err;
        console.log('Rename complete!');
    });
}
于 2019-06-18T07:48:51.297 回答