如果您的 node express web 服务在 linux 服务器 (ubuntu) 上并且您需要从 windows 服务器下载文件,您如何检索文件?
2 个有效选项:
Windows 服务器不支持 SFTP/SSH。有一些方法可以做到这一点(使用 https://winscp.net/eng/docs/guide_windows_openssh_server 和 https://www.npmjs.com/package/ssh2 )但这需要我们的服务器管理员在 Windows 上安装并且它不受 Microsoft 的完全支持。
您可以使用 FTP/FTPS。有这个包裹:https://github.com/Atinux/node-ftps我只是无法让它发挥作用,但它应该是一个可行的选择。
如何直接从操作系统而不是依赖第三方 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/