简体   繁体   中英

Node - Write JSON result to a file after a promise

I am using request-promise to fetch data from an api. I need to write the results to a json file. Following code doesn't write anything to the file.

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...
    });

I have tried this also, but that didn't worked out either.

Best and easy way to write on file:

.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)
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM