比方說,我有一個文件「/tmp/sample.txt」,我想將它移動到「/var/www/mysite/sample.txt」,這是在不同的音量。移動文件與node.js的
如何在node.js中移動文件?
,我讀了fs.rename只能在同一個卷內,util.pump已經過時。
什麼是正確的方法來做到這一點?我讀了關於stream.pipe的內容,但是我無法實現它。一個簡單的示例代碼將非常有幫助。
比方說,我有一個文件「/tmp/sample.txt」,我想將它移動到「/var/www/mysite/sample.txt」,這是在不同的音量。移動文件與node.js的
如何在node.js中移動文件?
,我讀了fs.rename只能在同一個卷內,util.pump已經過時。
什麼是正確的方法來做到這一點?我讀了關於stream.pipe的內容,但是我無法實現它。一個簡單的示例代碼將非常有幫助。
使用mv module:
var mv = require('mv');
mv('source', 'dest', function(err) {
// handle the error
});
MV的模塊,如說jbowes,可能是正確的道路要走,但你可以使用子進程API,並使用內置的操作系統工具作爲一種替代。如果您在Linux中使用「mv」命令。如果您在Windows中,請使用「移動」命令。
var exec = require('child_process').exec;
exec('mv /temp/sample.txt /var/www/mysite/sample.txt',
function(err, stdout, stderr) {
// stdout is a string containing the output of the command.
});
我會堅持mv模塊,但+1;) –
如果在Windows和沒有「MV」模塊,我們可以這樣做
var fs = require("fs"),
source = fs.createReadStream("c:/sample.txt"),
destination = fs.createWriteStream("d:/sample.txt");
source.pipe(destination, { end: false });
source.on("end", function(){
fs.unlinkSync("C:/move.txt");
});
您還可以使用產卵,如果高管不能正常工作。
var spawn = require("child_process").spawn;
var child = spawn("mv", ["data.csv","./done/"]);
child.stdout.on("end", function() {
return next(null,"finished")
});
希望這可以幫助你。
工程就像一個魅力。謝謝! –
是否可以將文件從一臺服務器移動到另一臺服務器? –
這似乎不適用於Windows。 –