如何将文件a移动到Node.js中的其他分区或设备?

我试图将一个文件从一个分区移动到另一个Node.js脚本中。 当我使用fs.renameSync收到Error: EXDEV, Cross-device link 。 我会复制它,并删除原来的,但我没有看到一个命令来复制文件。 如何才能做到这一点?

在跨不同分区移动文件时,您需要复制和取消链接。 尝试这个,

 var fs = require('fs'); //var util = require('util'); var is = fs.createReadStream('source_file'); var os = fs.createWriteStream('destination_file'); is.pipe(os); is.on('end',function() { fs.unlinkSync('source_file'); }); /* node.js 0.6 and earlier you can use util.pump: util.pump(is, os, function() { fs.unlinkSync('source_file'); }); */ 

还有一个解决问题的办法。

在npm上有一个叫“coolaj86”的包,叫fs.extra 。

你这样使用它: npm install fs.extra

 fs = require ('fs.extra'); fs.move ('foo.txt', 'bar.txt', function (err) { if (err) { throw err; } console.log ("Moved 'foo.txt' to 'bar.txt'"); }); 

我已经阅读了这个东西的源代码。 它试图做一个标准的fs.rename()然后,如果失败,它会复制并删除使用util.pump()使用的相同util.pump()的原始文件。

我知道这已经回答了,但是我遇到了类似的问题,最后得到了一些结论:

 require('child_process').spawn('cp', ['-r', source, destination]) 

这就是调用命令cp (“copy”)。 由于我们正在脱离Node.js,所以这个命令需要你的系统支持。

我知道这不是最优雅的,但它做了我所需要的:)

导入模块并将其保存到您的package.json文件中

 npm install mv --save 

然后像这样使用它:

 var mv = require('mv'); mv('source_file', 'destination_file', function (err) { if (err) { throw err; } console.log('file moved successfully'); }); 

我做了一个Node.js模块,只为你处理它。 您不必考虑是否要在同一分区内移动。 这是最快的解决scheme,因为它使用最近的fs.copyFile() Node.js API在移动到不同的分区/磁盘时复制文件。

只需安装move-file

 $ npm install move-file 

然后像这样使用它:

 const moveFile = require('move-file'); (async () => { await moveFile(fromPath, toPath); console.log('File moved'); })();