1

如果您的 node express web 服务位于 linux 服务器 (ubuntu) 上并且您需要从 windows 服务器下载文件,您如何检索文件?

2 个有效选项:

你怎么能直接从操作系统而不是依赖第三方节点包来做到这一点?

4

1 回答 1

3

您可以使用 smbget( https://linux.die.net/man/1/smbget附带的 linux 实用程序),然后只需使用 node 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 浏览器知道提示用户下载文件。

于 2017-05-26T14:15:51.633 回答