Node.js将远程文件复制到服务器

时间:2010-11-13 18:21:17

标签: javascript node.js

现在我在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中的方法吗?

3 个答案:

答案 0 :(得分:5)

您应该查看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);
  });
});

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

答案 1 :(得分: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;
    }
}

答案 2 :(得分:0)

如果由于某些原因无法使用远程用户密码并需要使用身份密钥(RSA)进行身份验证,则以编程方式scp执行child_processconst { 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}`); }); 很高兴

// No "block" implies return
const createSchema = () =>
  Business.findAll({ raw: true})
    .then((data) => 
      // wrap Promise.all and map() instead of forEach()
      Promise.all(
        data.map((client) =>
          postgresDB.createSchema(client.code).then(() => 
            // Again wrap Promise.all and map()
            Promise.all(
              Object.keys(postgresDB.models).map((currentItem) => 
                postgresDB.models[currentItem].schema(client.code).sync()
              )
            )
          )
        )
      )
    )
    .then(() => console.log("now I'm done"))
    //.catch((err) => console.log('Warning:', err.message));