如何使用fs.watchFile重新加载Json文件

时间:2018-08-21 16:41:12

标签: node.js

我有几个重新构造JSON文件的函数。他们彼此写作和操纵。它们在同一个js文件中。每个功能都取决于该功能才能正常运行。但是由于他们每个人都在读取文件后同步操作该文件,因此我遇到了一个难以解释的问题,因为我不确定我是否理解得很好。当第一个函数完成任务时,第二个函数无法读取它(它读取但看不到更新的对象及其属性)。如果我一个接一个地运行所有功能,然后重新启动程序,它的读取效果很好。这是我到目前为止尝试过的;

  • 我试图使函数异步化
  • 我尝试使用setTimeout函数并将其放弃直到10秒

两者都不适合我。我在StackOverflow中阅读到它fs.watch可以帮助我,但找不到有关如何实现该功能的适当说明。我对此问题的任何帮助将不胜感激。

-我知道我可以使用另一个数据库,但是我只想知道这个数据库,因为我经常使用它。如果我很傻,请不要粗鲁:P

const fs = require('fs');
const ReadRawData= fs.readFileSync('Data.json');
const ReadParsed = JSON.parse(ReadRawData);

fs.watchFile('Data.json', (curr, prev) => {
    console.log(`the current mtime is: ${curr.mtime}`);
    console.log(`the previous mtime was: ${prev.mtime}`);
});

我只想知道每次文件更改后如何重新加载此ReadParsed,并且可以从函数访问重新加载的版本。

这是我的完整代码;这是testing2.js

const request = require('request');
const cherio= require('cheerio');
const fs = require('fs');
const cheerioTableparser = require('cheerio-tableparser');


async function htmlCollector () {
    const ReadTransactionBase = await fs.readFileSync('transactionDatabase.json');
    const ReadTransaction = JSON.parse(ReadTransactionBase);
    ReadTransaction.pageInformation = "";
    let editedDataBase = JSON.stringify(ReadTransaction, null, 2);
    fs.writeFileSync('transactionDatabase.json', editedDataBase);
    for (let counter = 1; counter <= ReadTransaction.maxPage; counter++) {
        request(ReadTransaction.link + counter,
            (error, response, html) => {
                if (!error && response.statusCode === 200) {
                    const $ = cherio.load(html);
                    const items = [];
                    $('#maindiv').each(function (i, elem) {
                        items[i] = $(this).html();
                    });
                    let newPage = {['PageNumber'+counter] : items};
                    ReadTransaction.pageInformation = Object.assign(newPage,ReadTransaction.pageInformation);
                    let editedDataBase = JSON.stringify(ReadTransaction, null, 2);
                    fs.writeFileSync('transactionDatabase.json', editedDataBase);
                }
            })
    }
}

async function databaseModifier () {
    const ReadTransactionBase = await fs.readFileSync('transactionDatabase.json');
    const ReadTransaction = JSON.parse(ReadTransactionBase);
    delete ReadTransaction.from;
    delete ReadTransaction.quantities;
    delete ReadTransaction.orangeBox;
    let editedDataBase = JSON.stringify(ReadTransaction, null, 2);
    console.log('test');
    fs.writeFileSync('transactionDatabase.json', editedDataBase);
    for (let i=1; i<=Object.keys(ReadTransaction.pageInformation).length;i++) {
        let nums = 'PageNumber' + i;
        let newObject = {[nums]: {}};
        ReadTransaction.from = Object.assign(newObject,ReadTransaction.from);
        ReadTransaction.orangeBox = Object.assign(newObject,ReadTransaction.orangeBox);
        ReadTransaction.quantities = Object.assign(newObject,ReadTransaction.quantities);
        let editedDataBase = JSON.stringify(ReadTransaction, null, 2);
        fs.writeFileSync('transactionDatabase.json', editedDataBase);
    }
}

async function fromOrangeBoxQuantities () {
    const ReadTransactionBase = await fs.readFileSync('transactionDatabase.json');
    const ReadTransaction = JSON.parse(ReadTransactionBase);
    for (let counter = 1; counter <= ReadTransaction.maxPage ; counter++) {
        let HTMLPageNumber = 'PageNumber' + counter;
        let $ = cherio.load(ReadTransaction.pageInformation[HTMLPageNumber][0]);
        cheerioTableparser($);
        let data = $('.table').parsetable(true,true,true);
        for (let sCounter = 1; sCounter <= data[2].length; sCounter++) {
            let fromTable = {[sCounter] : [data[2][sCounter-1]]};
            let orangeBoxTable = {[sCounter] : [data[3][sCounter-1]]};
            let quantityTable = {[sCounter] : [data[5][sCounter-1]]};
            ReadTransaction.from[HTMLPageNumber] = Object.assign(fromTable,ReadTransaction.from[HTMLPageNumber]);
            ReadTransaction.orangeBox[HTMLPageNumber] = Object.assign(orangeBoxTable,ReadTransaction.orangeBox[HTMLPageNumber]);
            ReadTransaction.quantities[HTMLPageNumber] = Object.assign(quantityTable,ReadTransaction.quantities[HTMLPageNumber]);
            let editedDataBase = JSON.stringify(ReadTransaction, null, 2);
            fs.writeFileSync('transactionDatabase.json', editedDataBase);
        }
    }
}

async function validatorOfTransactions (){
    const ReadTransactionBase = await fs.readFileSync('transactionDatabase.json');
    const ReadTransaction = JSON.parse(ReadTransactionBase);
    ReadTransaction.validQuantities = [];
    let editedDataBase = JSON.stringify(ReadTransaction, null, 2);
    fs.writeFileSync('transactionDatabase.json', editedDataBase);
    for (let counter = 1; counter <= ReadTransaction.maxPage ; counter++) {
        let HTMLPageNumber = 'PageNumber' + counter;
        let length = Object.keys(ReadTransaction.from[HTMLPageNumber]).length;
        for (let sCounter = 1; sCounter <= length; sCounter++) {
            let a = ReadTransaction.from[HTMLPageNumber][sCounter].toString();
            let b = ReadTransaction.fromAddress;
            let c = ReadTransaction.orangeBox[HTMLPageNumber][sCounter].toString();
            let d = ReadTransaction.OrangeBox;
            if (a === b && c === d) {
                console.log('yay');
                ReadTransaction.validQuantities.push(parseFloat(ReadTransaction.quantities[HTMLPageNumber][sCounter].toString().replace(/,/g,'')));
                let editedDataBase = JSON.stringify(ReadTransaction, null, 2);
                fs.writeFileSync('transactionDatabase.json', editedDataBase);
            }
        }
    }
}

async function finalizeCalculation () {
    const ReadTransactionBase = await fs.readFileSync('transactionDatabase.json');
    const ReadTransaction = JSON.parse(ReadTransactionBase);
    let NewArray = ReadTransaction.validQuantities;
    return NewArray.reduce((a,b) => a +b, 0);
}


module.exports = {
    htmlCollector : htmlCollector,
    databaseModifier : databaseModifier,
    fromOrangeBoxQuantities : fromOrangeBoxQuantities,
    validatorOfTransactions : validatorOfTransactions,
    finalizeCalculation : finalizeCalculation
};

这是transactionDatabase.json;

{
  "link": "https://etherscan.io/token/generic-tokentxns2?contractAddress=0xaf2de5cb07d8f5de2369ff104150fef9dc0e604b&mode=&a=0x11209cbc2ea8cf829aa5aa1cdc5a4e5962e70655&p=",
  "maxPage": 12,
  "fromAddress": "0x11209cbc2ea8cf829aa5aa1cdc5a4e5962e70655",
  "OrangeBox": "OUT",
  "validQuantities": [],
  "pageInformation": {}
}

这是newtest.js;

let testing2 = require('./testing2');

testing2.htmlCollector().then(() => testing2.databaseModifier().then(()=> testing2.fromOrangeBoxQuantities().then(()=> testing2.validatorOfTransactions().then())));

这是我遇到的错误;

(节点:21760)UnhandledPromiseRejectionWarning:TypeError:无法读取未定义的属性“ 0”

0 个答案:

没有答案