如何使用 node.js 复制 wget 的功能?
Posted
技术标签:
【中文标题】如何使用 node.js 复制 wget 的功能?【英文标题】:How can I replicate the functionality of a wget with node.js? 【发布时间】:2012-03-21 10:06:51 【问题描述】:是否可以从 node.js 应用程序中运行wget
?我想要一个爬取站点并下载特定文件的脚本,但是该文件的链接的href
经常更改。所以,我认为最简单的方法是找到链接的href
,然后对其执行 wget。
谢谢!
【问题讨论】:
查看child_process.exec(cmd)
的 node.js 文档。
所有当前的答案都太复杂了。有一个文件流的简单解决方案。 ***.com/questions/11944932/…
【参考方案1】:
您可以使用 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);
);
【讨论】:
这回答了问题,但是当您可以使用请求时为什么要这样做?【参考方案2】:你可以只使用 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");
);
【讨论】:
【参考方案3】:不过,为了将来参考,我会推荐 request,这样可以很容易地获取该文件:
var request = require("request");
request(url, function(err, res, body)
// Do funky stuff with body
);
【讨论】:
【参考方案4】:虽然它可能比一些第三方的东西更冗长,但 Node 的核心 HTTP
模块提供了一个 HTTP client,您可以使用它:
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);
);
【讨论】:
我喜欢这个答案只使用核心节点库。干得好 如果您正在寻找更少的工作,而不添加依赖项,使用内置的url
模块的 parse
方法将产生一个您可以使用的对象,而不是构建 options
. (假设您已经有一个字符串 URI 可以传递给它)。【参考方案5】:
您可以使用node-wget。 在无法使用“wget”的情况下工作
【讨论】:
以上是关于如何使用 node.js 复制 wget 的功能?的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 nvm 设置默认 Node.js 版本? [复制]
如何使用 Node.js 动态生成 Html 内容? [复制]
如何使用Node.js Express执行Python函数[复制]