解决Node.js调用fs.renameSync报错的问题(Error: EXDEV, cross-device link not permitted)
2014-08-23
今天开始学习Node.js,在写一个文件上传的功能时候,调用fs.renameSync方法错误
出错代码所在如下:
1 function upload(response,request){ 2 console.log("upload called"); 3 var form = new formidable.IncomingForm(); 4 console.log("about to parse"); 5 form.parse(request, function(error, fields, files) { 6 console.log("parsing done"); 7 fs.renameSync(files.upload.path, "./tmp/test.jpg"); 8 response.writeHead(200, {"Content-Type": "text/html"}); 9 response.write("received image:<br/>"); 10 response.write("<img src='/show' />"); 11 response.end(); 12 }); 13 }
大致分析后,预计是因为跨磁盘分区移动或操作文件会有权限问题。
下面提供两种解决办法:
方法一:
主要利用fs的createReadStream、createWriteSream和unlinkSync方法
具体代码如下:
1 function upload(response,request){ 2 console.log("upload called"); 3 var form = new formidable.IncomingForm(); 4 console.log("about to parse"); 5 form.parse(request, function(error, fields, files) { 6 console.log("parsing done");
7 // fs.renameSync(files.upload.path, "./tmp/test.jpg"); 8 var readStream=fs.createReadStream(files.upload.path); 9 var writeStream=fs.createWriteStream("./tmp/test.jpg"); 10 readStream.pipe(writeStream); 11 readStream.on('end',function(){ 12 fs.unlinkSync(files.upload.path); 13 });
14 response.writeHead(200, {"Content-Type": "text/html"}); 15 response.write("received image:<br/>"); 16 response.write("<img src='/show' />"); 17 response.end(); 18 }); 19 }
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' 即可(写一个临时路径)
1 function upload(response,request){ 2 console.log("upload called"); 3 var form = new formidable.IncomingForm(); 4 form.uploadDir='tmp'; 5 6 console.log("about to parse"); 7 form.parse(request, function(error, fields, files) { 8 console.log("parsing done"); 9 fs.renameSync(files.upload.path, "./tmp/test.jpg"); 10 response.writeHead(200, {"Content-Type": "text/html"}); 11 response.write("received image:<br/>"); 12 response.write("<img src='/show' />"); 13 response.end(); 14 }); 15 } 16
解决问题后,就可以很开心的继续我的Node学习了,感觉路还很长啊
PS:附上两个有关Node文件上传的帖子,个人觉得挺不错的,来源都是cnode