簡體   English   中英

節點-承諾后將JSON結果寫入文件

[英]Node - Write JSON result to a file after a promise

我正在使用請求承諾從api獲取數據。 我需要將結果寫入json文件。 以下代碼不會向文件寫入任何內容。

var rp = require('request-promise');
rp(empOptions)
    .then(function (repos) {
        employees= repos;
        return new Promise(function(resolve, reject) {
            fs.writeFile('../employees.json', JSON.stringify(employees), function(err) {
                if (err) reject(err);
            });
        });
    })
    .catch(function (err) {
        // API call failed...
    });

我已經試過也,但沒有任何解決。

記錄文件的最佳簡便方法:

.then(function(results) {
    return new Promise(function(resolve, reject) {
        fs.appendFileSync('myurlss2.json', results, function(err) {
            if (err) reject(err)
            else resolve(results)
        })
    })
})
.then(function(results) {
    console.log("results here: " + results)
})
.catch(function(err) {
    console.log("error here: " + err)
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM