node.js - 使用 smbget 在 Node js 中从 Windows 转移到 Linux

标签 node.js linux libsmbclient

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

2 个有效选项:

如何直接从操作系统而不是依赖第三方 Node 包来执行此操作?

最佳答案

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

只需将 [工作组]、[用户名]、[密码]、[服务器地址] 和 [路径] 替换为您自己的信息即可。

 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);
    })
  })
}

上面的代码片段返回一个 promise 。因此,在 Node 中,您可以将响应发送到这样的路由:

 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 发送带有响应的正确 header ,以便大多数现代网络浏览器知道提示用户下载文件。

关于node.js - 使用 smbget 在 Node js 中从 Windows 转移到 Linux,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44203845/

相关文章:

c - 为什么linux中不混合标准输入?

libsmbclient - 如何使用 smbclient 将结果从管道传输到 Samba 驱动器?

mysql - Sequelize : How to make use of multiple operators to create a fetch of objects with an exclusion clause

javascript - 使用Sinon的Mongoose模型的 stub 保存实例方法

python - 抓取 Telegram channel 以进行更改

linux - 使用 bash 脚本从具有相同文件夹名称 XML 的不同位置删除超过 4 周的 xml 文件

linux - centos linux 上的 dotnet 恢复错误 : access to path denied

linux - smbclient 从 Linux 连接到 Windows 目录

node.js - 在使用electronic-builder构建的 Electron 应用程序中包含Bootstrap