如何将字符添加到JSON文件的末尾?

时间:2018-10-07 09:13:24

标签: javascript json

我正在尝试做一些简单的事情,但是我正在努力!下面的代码可以成功运行(我将其包括在内,如图所示,这也可能对某人有用!),我要做的就是在第二个for循环之后,向文件末尾添加一些字符。我尝试重用fs.writeFileSync以及其他fs选项,但没有成功。有什么建议吗?

const watson = require("../../src/api/WatsonSingleton.js");
const fs = require("fs");
const DATASETS_PATH = "./workspaces/";
const workspaceFilenames = ["workspace_abroad.json"];

let outputText = "[\n";

for(let filename of workspaceFilenames) { // Loop through filenames defined in `workspaceFilenames`
    let workspace = require(`${DATASETS_PATH}${filename}`);

    for(let intentDefinition of workspace.intents) { // Loop through intents to return examples
        let examples = intentDefinition.examples;

        for(let example of examples) {

            var promise1 = new Promise(function(resolve, reject) { // set promise to throttle tests so the next sendMessage occurs only after the previous sendMessage has returned a full response
                setTimeout(function() {
                               resolve(watson.sendMessage(example.text).catch(console.error));
                }, 2000);
            });

            promise1.then(function(res) { // Execute the promise and append response to a file
                outputText += "    " + JSON.stringify(res) + ",\n";
                console.log(res);
                fs.writeFileSync("../report/workspaces/" + filename, outputText); // Append report file with response data
            });
        }
    }
}

1 个答案:

答案 0 :(得分:1)

首先,如果您想使用setTimeout来限制循环,它将无法正常工作。由于setTimeout不阻塞,因此循环将继续执行,因此所有请求仍将立即发送-延迟2秒后。您要做的是等待watson.sendMessage在每次迭代中完成。我曾经使用async / await方法来实现这一目标。

这也使代码更简单,而无需创建Promise。您的循环应如下所示:

 // Loop through intents to return examples
for(let intentDefinition of workspace.intents) {
    intentDefinition.examples.forEach(async function() {
        try {
          const res = await watson.sendMessage(example.text);
          console.log(res);
          outputText += "    " + JSON.stringify(res) + ",\n";

          // Append report file with response data
          fs.writeFileSync("../report/workspaces/" + filename, outputText); 
        } catch (e) {
          console.error(e);
        }
    });
}