Node.js将远程文件复制到服务器 [英] Node.js copy remote file to server

查看:186
本文介绍了Node.js将远程文件复制到服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我在PHP中使用这个脚本。我传递图像和大小(大/中/小),如果它在我的服务器上它返回链接,否则它从远程服务器复制它然后返回本地链接。

Right now I'm using this script in PHP. I pass it the image and size (large/medium/small) and if it's on my server it returns the link, otherwise it copies it from a remote server then returns the local link.

function getImage ($img, $size) {
    if (@filesize("./images/".$size."/".$img.".jpg")) {
        return './images/'.$size.'/'.$img.'.jpg';
    } else {
        copy('http://www.othersite.com/images/'.$size.'/'.$img.'.jpg', './images/'.$size.'/'.$img.'.jpg');
        return './images/'.$size.'/'.$img.'.jpg';
    }
}

它工作正常,但我正在尝试做在Node.js中同样的事情,我似乎无法弄明白。文件系统似乎无法与任何远程服务器进行交互,所以我想知道我是不是只是弄乱了一些东西,或者它是不是本地完成而且需要一个模块。

It works fine, but I'm trying to do the same thing in Node.js and I can't seem to figure it out. The filesystem seems to be unable to interact with any remote servers so I'm wondering if I'm just messing something up, or if it can't be done natively and a module will be required.

任何人都知道Node.js的方法吗?

Anyone know of a way in Node.js?

推荐答案

你应该看看 http.Client http.ClientResponse 。使用那些可以向远程服务器发出请求并使用将响应写出到本地文件fs.WriteStream

You should check out http.Client and http.ClientResponse. Using those you can make a request to the remote server and write out the response to a local file using fs.WriteStream.

这样的事情:

var http = require('http');
var fs = require('fs');
var google = http.createClient(80, 'www.google.com');
var request = google.request('GET', '/',
  {'host': 'www.google.com'});
request.end();
out = fs.createWriteStream('out');
request.on('response', function (response) {
  response.setEncoding('utf8');
  response.on('data', function (chunk) {
    out.write(chunk);
  });
});

我没有测试过,我不确定它是否可以开箱即用。但我希望它会引导你到达你需要的东西。

I haven't tested that, and I'm not sure it'll work out of the box. But I hope it'll guide you to what you need.

这篇关于Node.js将远程文件复制到服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆