承诺中的 fs.writeFile,异步同步的东西东西、fs、writeFile

2023-09-07 15:50:57 作者:蓝色条纹西装

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

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

我正在尝试做的事情:

1) 获取包含亚马逊产品 (ASIN) 的 .txt;

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

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

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

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

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

推荐答案

截至 2019...

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

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.

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

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.

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

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');
})();