javascript - Node.js 强制等待函数完成

标签 javascript node.js file npm x-ray

我在使用 Node.js 运行的程序中有一个 for 循环。该函数是来自 xray 的 x()包,我用它从网页上抓取和接收数据,然后将该数据写入文件。该程序用于抓取 ~100 页时是成功的,但我需要抓取 ~10000 页。当我尝试抓取大量页面时,会创建文件但它们不包含任何数据。我相信存在这个问题是因为 for 循环在继续下一次迭代之前不等待 x() 返回数据。

有没有办法让 Node 在进入下一次迭代之前等待 x() 函数完成?

//takes in file of urls, 1 on each line, and splits them into an array. 
//Then scrapes webpages and writes content to a file named for the pmid number that represents the study
 
//split urls into arrays
var fs = require('fs');
var array = fs.readFileSync('Desktop/formatted_urls.txt').toString().split("\n");


var Xray = require('x-ray');
var x = new Xray();
 
for(i in array){
        //get unique number and url from the array to be put into the text file name
                number = array[i].substring(35);
                url = array[i];


        //use .write function of x from xray to write the info to a file
        x(url, 'css selectors').write('filepath' + number + '.txt');
                               
}

注意:我抓取的一些页面没有返回任何值

最佳答案

您的代码的问题是您没有等待将文件写入文件系统。 比一个一个地下载文件更好的方法是一次完成,然后等到它们完成,而不是一个一个地处理它们然后再继续下一个。

在 nodejs 中处理 promise 的推荐库之一是 bluebird。

http://bluebirdjs.com/docs/getting-started.html

在更新的示例中(见下文),我们遍历所有 url 并开始下载,并跟踪 promise ,然后一旦文件被写入,每个 promise 就会被解决。 最后,我们只是等待所有的 promise 使用 Promise.all() 得到解决

这是更新后的代码:

var promises = [];
var getDownloadPromise = function(url, number){
    return new Promise(function(resolve){
        x(url, 'css selectors').write('filepath' + number + '.txt').on('finish', function(){
            console.log('Completed ' + url);
            resolve();
        });
    });
};

for(i in array){
    number = array[i].substring(35);
    url = array[i];

    promises.push(getDownloadPromise(url, number));                               
}

Promise.all(promises).then(function(){
    console.log('All urls have been completed');
});

关于javascript - Node.js 强制等待函数完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33748608/

相关文章:

javascript - 将 Javascript 日期对象转换为 PST 时区

javascript - 为什么在这种情况下触发和点击不起作用?

javascript - {{#each objects}} 对比 {{#each model.objects}} 对比 {{#each content.objects}}

javascript - GET 请求不会仅在 Node.JS 内返回?

java - 在java中检查文件创建权限的最佳方法是什么

javascript - 如果已匹配 HTML5 输入模式,如何在 JS 中进行验证?

javascript - 无法在 Sequelize 中插入具有不可为空外键的行

node.js - 无法使用 Ctrl + C 停止本地 Node 服务器 (Mac)

java - JAVA中如何从目录的子文件夹中读取特定类型的文件

使用超过 1 个缓冲区复制二进制文件会导致错误的 md5 校验和