在Node.js中找到2个文件之间的差异

时间:2019-06-24 14:39:00

标签: node.js filesystems

我有2个具有静态数据的json文件。

文件A.json

{
"data": ["A","B","C","D"]
}

文件B.json

{
"data":["A","B","C"]
}

现在我想找到这两个文件之间的区别。

我尝试使用此代码按名称获取文件

const express = require("express");
const jsonfile = require("jsonfile");
const app = express();
const fs  = require("fs");

app.use(express.json());

const BASEPATH = "./data"

app.get("/api/v1/data/:name", async (req,res) =>  {
const fileName = req.params.name;
const filePath = `${BASEPATH}/${fileName}.json`
try {
    const readData = await jsonfile.readFile(filePath);
    res.status(200).json(readData);
}catch (e) {
    res.status(404).send(e);
}
});

URL为:localhost:3000 / api / v1 / data / A

要添加我使用的数据,

app.put("/api/v1/data",(req,res) => {
const fileName = req.body.name;
const data = req.body.data;

const filePath = `${BASEPATH}/${fileName}.json`

fs.exists(filePath, async exists => {
    if(exists) {
        try {
            await jsonfile.writeFile(filePath,{data:data});
            res.status(200).send();
        }catch(e) {
            res.send(500).json(e);
        }
    } else {
        try {
            await jsonfile.writeFile(filePath,{data:data});
            res.status(201).send();
        }catch(e) {
            res.send(500).json(e);
        }
    }
})
});

添加的数据示例:

{ "name":"C", "data":["A","B","Z"]}

URL为:localhost:3000 / api / v1 / data

1 个答案:

答案 0 :(得分:0)

您可以尝试这样

app.get("/api/v1/data/diff", async (req,res) => {
try {
    const file1 = req.query.file1;
    const file2 = req.query.file2;
    console.log(file1,file2)
    if(file1 === undefined || file2 === undefined ) {
        res.status(401).send("BAD REQUEST. SEND FILE NAMES");
        return;   
    } else {
        const filePath1 = `${BASEPATH}/${file1}.json`
        const filePath2 = `${BASEPATH}/${file2}.json`

        const file1Data = await jsonfile.readFile(filePath1);
        const file2Data = await jsonfile.readFile(filePath2);

        let difference = file1Data.data.filter(x => !file2Data.data.includes(x));
        let difference2 = file2Data.data.filter(x => !file1Data.data.includes(x));

        res.status(200).json({diff: [...difference,...difference2]});
    }
}catch(e) {
    res.status(500).json(e);
}
});

您必须使用以下网址:localhost:3000 / api / v1 / data / diff?file1 = A&file2 = B

输出将为

{      “ diff”:[         “ D”      ]    }

相关问题