繁体   English   中英

如何使用node.js复制wget的功能?

[英]How can I replicate the functionality of a wget with node.js?

是否有可能从node.js应用程序中运行wget 我想要一个抓取网站的脚本,然后下载一个特定的文件,但是文件链接的href会经常发生变化。 因此,我认为最简单的方法是找到链接的href ,然后只需对它执行wget即可。

谢谢!

但是为了将来参考,我建议使用request ,这样可以很容易地获取该文件:

var request = require("request");

request(url, function(err, res, body) {
  // Do funky stuff with body
});

虽然它可能比某些第三方内容更冗长,但Node的核心HTTP模块提供了一个可用于此的HTTP客户端

var http = require('http');
var options = {
    host: 'www.site2scrape.com',
    port: 80,
    path: '/page/scrape_me.html'
  };
var req = http.get(options, function(response) {
  // handle the response
  var res_data = '';
  response.on('data', function(chunk) {
    res_data += chunk;
  });
  response.on('end', function() {
    console.log(res_data);
  });
});
req.on('error', function(err) {
  console.log("Request error: " + err.message);
});

您可以使用child_processes运行外部命令:

http://nodejs.org/docs/latest/api/child_process.html#child_process_child_process_exec_command_options_callback

var util = require('util'),
    exec = require('child_process').exec,
    child,
    url = 'url to file';

child = exec('wget ' + url,
  function (error, stdout, stderr) {
    console.log('stdout: ' + stdout);
    console.log('stderr: ' + stderr);
    if (error !== null) {
      console.log('exec error: ' + error);
    }
});

您可以使用node-wget 适用于无法“wget”的情况

你可以使用wget。

var exec = require('child_process').exec;

child = exec("/path/to/wget http://some.domain/some.file", function (error, stdout, stderr) {
if (error !== null) {
  console.log("ERROR: " + error);
}
else {
  console.log("YEAH IT WORKED");
}
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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