這篇文章主要介紹了Node.js調用fs.renameSync報錯(Error: EXDEV, cross-device link not permitted),非常具有實用價值,需要的朋友可以參考下
在寫一個檔案上傳的功能時候,呼叫fs.renameSync方法錯誤
出錯程式碼所在如下:
function upload(response,request){ console.log("upload called"); var form = new formidable.IncomingForm(); console.log("about to parse"); form.parse(request, function(error, fields, files) { console.log("parsing done"); fs.renameSync(files.upload.path, "./tmp/test.jpg"); response.writeHead(200, {"Content-Type": "text/html"}); response.write("received image:<br/>"); response.write("<img src='/show' />"); response.end(); }); }
大致分析後,預計是因為跨磁碟分割區移動或操作檔案會有權限問題。
下面提供兩種解決方法:
方法一:
主要利用fs的createReadStream、createWriteSream和unlinkSync方法
具體程式碼如下:
function upload(response,request){ console.log("upload called"); var form = new formidable.IncomingForm(); console.log("about to parse"); form.parse(request, function(error, fields, files) { console.log("parsing done"); // fs.renameSync(files.upload.path, "./tmp/test.jpg"); var readStream=fs.createReadStream(files.upload.path); var writeStream=fs.createWriteStream("./tmp/test.jpg"); readStream.pipe(writeStream); readStream.on('end',function(){ fs.unlinkSync(files.upload.path); }); response.writeHead(200, {"Content-Type": "text/html"}); response.write("received image:<br/>"); response.write("<img src='/show' />"); response.end(); }); }
PS:我用的node版本是0.10.69,如果使用的是0.6以下的版本,可以使用util.pump
#對應程式碼只要將上面的程式碼中readStream.on處改成:(注意引入util模組)
util.pump(readStream,writeStream, function() { fs.unlinkSync('files.upload.path'); });
方法二:
##這樣就簡潔很多了新增一個form.uploadDir='tmp' 即可(寫一個臨時路徑)function upload(response,request){ console.log("upload called"); var form = new formidable.IncomingForm(); form.uploadDir='tmp'; console.log("about to parse"); form.parse(request, function(error, fields, files) { console.log("parsing done"); fs.renameSync(files.upload.path, "./tmp/test.jpg"); response.writeHead(, {"Content-Type": "text/html"}); response.write("received image:<br/>"); response.write("<img src='/show' />"); response.end(); }); }上面是我整理給大家的,希望今後會對大家有幫助。 相關文章:
以上是在Node.js中呼叫fs.renameSync出現錯誤問題?的詳細內容。更多資訊請關注PHP中文網其他相關文章!