【问题标题】:I want to store values in file in json format using fs我想使用 fs 以 json 格式将值存储在文件中
【发布时间】:2022-01-14 00:05:24
【问题描述】:
            let AccountDetails = {
                dformat,
                username,
                password, 
                accountType,
                charity
            
        };
        AccountDetails.dformat
            let creds = JSON.stringify(AccountDetails);
            fs.appendFile("LoginID\\JsonCreds.json",creds,(err) => {
                if (err) {
                    console.log(err);
                }
                else {
                    // Get the file contents after the append operation
                    console.log("\nFile Contents of file after append:",
                        fs.readFileSync("LoginID\\JsonCreds.json", "utf8"));
                }
            });
Output:-{
    "dformat": "2021-12-09 10:09:53","username": "An191428","password": "Root@123","accountType": "Basic Enterprise Postpaid","charity": "Non-charity"
}

我希望输出如下:-2021-12-09 10:09:53|An191428|Root@123|Basic Enterprise Postpaid|Non-charity 像这样并且每次追加后还想要新行,请帮助我。

【问题讨论】:

    标签: node.js json testing automation fs


    【解决方案1】:

    您显示的 o/p 不是 JSON,请检查 here 什么是有效的 json。您可以将此数据写入文本文件而不是 JSON。首先,您需要获取值并创建一个格式相同的字符串并将其写入文本文件。

    const fs = require('fs');
      let AccountDetails = {
                    dformat,
                    username,
                    password, 
                    accountType,
                    charity
                
    };
    
    const dataFormatted = Object.values(AccountDetails).join('|');
    
    fs.writeFile('create Text file', dataFormatted, {flag: 'a+'}, err => {
      if (err) {
        console.error(err)
        return
      }
    })
    
    

    您还可以查看this 链接,了解如何在 Node.js 中写入文件。读取文本文件时,创建一个readLine接口,逐行读取,过滤掉结果。

    【讨论】:

    • 好的,我只想追加,因为每次执行都会覆盖写入。
    • Flag- a+ 会将流位置带到末尾并从那里追加。您需要确保文件存在且路径正确。
    • 希望这个答案有帮助。
    • 就像你说的,它不是 json ,我如何在 json 中存储相同的值?
    • 您将无法使用 .appendFile 并在文件中维护 JSON。 JSON 是一种文档格式,您需要能够将所有数据包装在一个整体结构中。您可能必须读取整个文件,添加数据并将其写出,如果同时写入多个内容,请小心
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-13
    • 2021-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-19
    • 2019-03-11
    相关资源
    最近更新 更多