本文主要是介绍解决Node.js调用fs.renameSync报错的问题(Error: EXDEV, cross-device link not permitted),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
在写一个文件上传的功能时候,调用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.js调用fs.renameSync报错的问题(Error: EXDEV, cross-device link not permitted)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!