2017-05-26 178 views
0

如果您的节点表达Web服务位于Linux服务器(ubuntu)并且您需要从Windows服务器下载文件,如何检索文件?使用smbget从节点js从Windows传输到Linux

2级有效的选项:

如何从操作系统直接执行此操作而不是依赖第三方节点程序包?

回答

2

您可以使用smbget(包含在https://linux.die.net/man/1/smbget中的linux实用程序),然后使用节点child_process spawn调用该函数。

只需在此处用您自己的信息替换[workgroup],[username],[password],[serveraddress]和[path]。

function getFile(file) { 
    return new Promise(function(resolve, reject) { 
    var tempFilePath = `/tmp/${file}`; // the linux machine 
    var remoteFile = require('child_process').spawn('smbget', ['--outputfile', tempFilePath, '--workgroup=[workgroup]', '-u', '[username]', '-p', '[password]', `smb://[serveraddress]/c$/[path]/[path]/${file}`]); 
    remoteFile.stdout.on('data', function(chunk) { 
    //  //handle chunk of data 
    }); 
    remoteFile.on('exit', function() { 
     //file loaded completely, continue doing stuff 

     // TODO: make sure the file exists on local drive before resolving.. an error should be returned if the file does not exist on WINDOWS machine 
     resolve(tempFilePath); 
    }); 
    remoteFile.on('error', function(err) { 
     reject(err); 
    }) 
    }) 
} 

上面的代码片段返回一个承诺。因此,在节点中,您可以将响应发送到如下路径:

var express = require('express'), 
router = express.Router(), 
retrieveFile = require('../[filename-where-above-function-is]'); 

router.route('/download/:file').get(function(req, res) { 
    retrieveFile.getFile(req.params.file).then(
     file => { 
      res.status(200); 
      res.download(file, function(err) { 
      if (err) { 
       // handle error, but keep in mind the response may be partially sent 
       // so check res.headersSent 
      } else { 
       // remove the temp file from this server 
       fs.unlinkSync(file); // this delete the file! 
      } 
      }); 
     }) 
     .catch(err => { 
     console.log(err); 
     res.status(500).json(err); 
     }) 
    } 

响应将是要下载文件的实际二进制文件。由于该文件是从远程服务器检索的,因此我们还需要确保使用fs.unlinkSync()删除本地文件。

使用res.download发送适当的标题与响应,以便大多数现代Web浏览器知道提示用户下载文件。