2012-11-08 34 views
2

比方說,我有一個文件「/tmp/sample.txt」,我想將它移動到「/var/www/mysite/sample.txt」,這是在不同的音量。移動文件與node.js的

如何在node.js中移動文件?

,我讀了fs.rename只能在同一個卷內,util.pump已經過時。

什麼是正確的方法來做到這一點?我讀了關於stream.pipe的內容,但是我無法實現它。一個簡單的示例代碼將非常有幫助。

回答

13

使用mv module

var mv = require('mv'); 

mv('source', 'dest', function(err) { 
    // handle the error 
}); 
+0

工程就像一個魅力。謝謝! –

+1

是否可以將文件從一臺服務器移動到另一臺服務器? –

+0

這似乎不適用於Windows。 –

1

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. 
}); 
+0

我會堅持mv模塊,但+1;) –

3

如果在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"); 
}); 
+0

您是否說mv模塊不能在Windows上工作? – nha

+0

@nha我的意思是不使用mv,如果我們想要這樣做。我在Windows上測試了代碼,所以.. – Tushkiz

+0

+1謝謝你的精確度。我通過管道流來測試WriteStream函數(就像在https://stackoverflow.com/questions/11944932/how-to-download-a-file-with-node-js中),它工作正常。重命名功能也是如此。但是我遇到了使用符號鏈接的問題(我通常不使用窗口)。 – nha

0

您還可以使用產卵,如果高管不能正常工作。

var spawn = require("child_process").spawn; 
var child = spawn("mv", ["data.csv","./done/"]); 
child.stdout.on("end", function() {     
    return next(null,"finished") 
}); 

希望這可以幫助你。