2017-05-26 174 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瀏覽器知道提示用戶下載文件。