fs.writeFile 在承诺中,异步同步的东西 [英] fs.writeFile in a promise, asynchronous-synchronous stuff

查看:30
本文介绍了fs.writeFile 在承诺中,异步同步的东西的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码需要一些帮助.我是 Node.js 的新手,遇到了很多麻烦.

我想做什么:

1) 使用亚马逊产品 (ASIN) 获取 .txt ;

2) 使用 amazon-product-api 包获取所有产品;

3) 将每个产品保存在 .json 文件中.

我的代码不起作用.我想我搞砸了这个异步-同步的东西 - 帮帮我!

var amazon = require('amazon-product-api');var fs = require('fs');var client = amazon.createClient({awsId: "XXX",awsSecret: "XXX",aws 标签:888"});var array = fs.readFileSync('./test.txt').toString().split('
');for (var i = 1; i < array.length; i++) {var ASIN = array[i];返回 client.itemLookup({域:'webservices.amazon.de',responseGroup: '大',idType: 'ASIN',商品编号:ASIN}).then(功能(结果){fs.writeFile(ASIN + '.json', JSON.stringify(results), function(err) {如果(错误){控制台日志(错误);} 别的 {console.log("JSON 已保存");}})返回结果;}).catch(函数(错误){控制台日志(错误);});};

解决方案

截至 2019...

...正确的答案是使用 async/await 和 node 中包含的原生 fs 承诺模块.升级到 Node.js 10 或 11(主要云提供商已经支持)并执行以下操作:

const fs = require('fs').promises;//这必须在标记为 `async` 的函数中运行:const file = await fs.readFile('filename.txt', 'utf8');等待 fs.writeFile('filename.txt', 'test');

不要使用第三方包,也不要编写自己的包装器,这已经没有必要了.

不再是实验性的

在 Node 11.14.0 之前,您仍然会收到警告,指出此功能是实验性的,但它运行良好,并且是未来的发展方向.从 11.14.0 开始,该功能不再是实验性的,可以投入生产.

如果我更喜欢 import 而不是 require 怎么办?

它也有效 - 但仅适用于此功能未标记为实验性的 Node.js 版本.

import { promises as fs } from 'fs';(异步() => {等待 fs.writeFile('./test.txt', 'test', 'utf8');})();

I need some help with my code. I'm new at Node.js and have a lot of trouble with it.

What I'm trying to do:

1) Fetch a .txt with Amazon products (ASINs) ;

2) Fetch all products using the amazon-product-api package;

3) Save each product in a .json file.

My code is not working. I think I messed up with this asynchronous-synchronous stuff - help me!

var amazon = require('amazon-product-api');
var fs = require('fs');

var client = amazon.createClient({
    awsId: "XXX",
    awsSecret: "XXX",
    awsTag: "888"
});

var array = fs.readFileSync('./test.txt').toString().split('
');
for (var i = 1; i < array.length; i++) {
     var ASIN = array[i];

    return client.itemLookup({
            domain: 'webservices.amazon.de',
            responseGroup: 'Large',
            idType: 'ASIN',
            itemId: ASIN
        })
        .then(function(results) {
            fs.writeFile(ASIN + '.json', JSON.stringify(results), function(err) {
                if (err) {
                    console.log(err);
                } else {
                    console.log("JSON saved");
                }
            })

            return results;

        }).catch(function(err) {
            console.log(err);
        });
};

解决方案

As of 2019...

...the correct answer is to use async/await with the native fs promises module included in node. Upgrade to Node.js 10 or 11 (already supported by major cloud providers) and do this:

const fs = require('fs').promises;

// This must run inside a function marked `async`:
const file = await fs.readFile('filename.txt', 'utf8');
await fs.writeFile('filename.txt', 'test');

Do not use third-party packages and do not write your own wrappers, that's not necessary anymore.

No longer experimental

Before Node 11.14.0, you would still get a warning that this feature is experimental, but it works just fine and it's the way to go in the future. Since 11.14.0, the feature is no longer experimental and is production-ready.

What if I prefer import instead of require?

It works, too - but only in Node.js versions where this feature is not marked as experimental.

import { promises as fs } from 'fs';

(async () => {
    await fs.writeFile('./test.txt', 'test', 'utf8');
})();

这篇关于fs.writeFile 在承诺中,异步同步的东西的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆