【问题标题】:Node.js copy remote file to serverNode.js 将远程文件复制到服务器
【发布时间】:2011-05-09 14:38:40
【问题描述】:

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

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 中做同样的事情,我似乎无法弄清楚。文件系统似乎无法与任何远程服务器交互,所以我想知道我是否只是搞砸了一些事情,或者它是否不能在本地完成并且需要一个模块。

有人知道 Node.js 中的一种方法吗?

【问题讨论】:

    标签: javascript node.js


    【解决方案1】:

    您应该查看http.Clienthttp.ClientResponse。使用这些,您可以向远程服务器发出请求,并使用 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);
      });
    });
    

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

    【讨论】:

    • 我测试了它,它确实“开箱即用”。谢谢!
    【解决方案2】:

    为了提供更更新的版本(因为最近的答案是 4 岁,并且 http.createClient 现在已弃用),这是使用 request 方法的解决方案:

    var fs = require('fs');
    var request = require('request');
    function getImage (img, size, filesize) {
        var imgPath = size + '/' + img + '.jpg';
        if (filesize) {
            return './images/' + imgPath;
        } else {
            request('http://www.othersite.com/images/' + imgPath).pipe(fs.createWriteStream('./images/' + imgPath))
            return './images/' + imgPath;
        }
    }
    

    【讨论】:

      【解决方案3】:

      如果由于某些原因您不能使用远程用户的密码并且需要使用身份密钥 (RSA) 进行身份验证,那么以编程方式执行 scpchild_process 很好

      const { exec } = require('child_process');
      
      exec(`scp -i /path/to/key username@example.com:/remote/path/to/file /local/path`, 
           (error, stdout, stderr) => {
      
          if (error) {
            console.log(`There was an error ${error}`);
          }
      
            console.log(`The stdout is ${stdout}`);
            console.log(`The stderr is ${stderr}`);
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-28
        • 2019-01-20
        • 2016-09-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-25
        相关资源
        最近更新 更多