How can I replicate the functionality of a wget wi

2019-03-12 23:12发布

Is it possible to essentially run a wget from within a node.js app? I'd like to have a script that crawls a site, and downloads a specific file, but the href of the link that goes the file changes fairly often. So, I figured the easiest way to go about doing it would be to find the href of the link, then just perform a wget on it.

Thanks!

5条回答
Luminary・发光体
2楼-- · 2019-03-12 23:37

For future reference though, I would recommend request, which makes it this easy to fetch that file:

var request = require("request");

request(url, function(err, res, body) {
  // Do funky stuff with body
});
查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-03-12 23:46

U can just use 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");
}
});
查看更多
甜甜的少女心
4楼-- · 2019-03-12 23:51

While it might be a little more verbose than some third-party stuff, Node's core HTTP module provides for an HTTP client you could use for this:

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);
});
查看更多
趁早两清
5楼-- · 2019-03-12 23:57

You can use node-wget. Works in cases where 'wget' is not possible

查看更多
Lonely孤独者°
6楼-- · 2019-03-13 00:00

You can run an external command using 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);
    }
});
查看更多
登录 后发表回答