最新消息:VPS服务器又从fzhost.net换回Linode了,主题仍用朋友推荐的大前端D8

【已解决】Node.js中所用的fs.renameSync出错:Error: EXDEV, cross-device link not permitted

Node.js crifan 1822浏览 0评论

【问题】

Win7下,折腾Node.js过程中,运行服务器,其中内部调用相关代码:

function show(response) {
  console.log("Request handler 'show' was called.");
  fs.readFile("/tmp/test.png", "binary", function(error, file) {
    if(error) {
      response.writeHead(500, {"Content-Type": "text/plain"});
      response.write(error + "\n");
      response.end();
    } else {
      response.writeHead(200, {"Content-Type": "image/png"});
      response.write(file, "binary");
      response.end();
    }
  });
}

去重命名,结果出错:

D:\tmp\tmp_dev_root\node.js>
D:\tmp\tmp_dev_root\node.js>node index.js
Server has started.
Request for /upload received.
About to route a request for /upload
Request handler 'upload' was called.
about to parse
parsing done

fs.js:439
  return binding.rename(pathModule._makeLong(oldPath),
                 ^
Error: EXDEV, cross-device link not permitted 'C:\Users\CLi\AppData\Local\Temp\df99513a93a1cbfbc26e076f8ae08b92'
    at Object.fs.renameSync (fs.js:439:18)
    at D:\tmp\tmp_dev_root\node.js\requestHandlers.js:34:8
    at IncomingForm.parse (D:\tmp\tmp_dev_root\node.js\node_modules\formidable\lib\incoming_form.js:121:9)
    at IncomingForm.EventEmitter.emit (events.js:93:17)
    at IncomingForm._maybeEnd (D:\tmp\tmp_dev_root\node.js\node_modules\formidable\lib\incoming_form.js:383:8)
    at IncomingForm.handlePart (D:\tmp\tmp_dev_root\node.js\node_modules\formidable\lib\incoming_form.js:212:12)
    at File.end (D:\tmp\tmp_dev_root\node.js\node_modules\formidable\lib\file.js:71:5)
    at WriteStream.flush (fs.js:1515:9)
    at Object.oncomplete (fs.js:297:15)

【解决过程】

1.参考:

Node.JS fs.rename doesn’t work

->

How do I move file a to a different partition in Node.js?

去试试代码:

var fs = require("fs"),
    util = require('util');
    ...
    //fs.renameSync(files.upload.path, "/tmp/test.png");
    
    var readStream = fs.createReadStream(files.upload.path)
    var writeStream = fs.createWriteStream("/tmp/test.png");
    
    util.pump(readStream, writeStream, function() {
        fs.unlinkSync(files.upload.path);
    });

 

最后,就可以实现跨分区重命名文件的功能了。

 

【总结】

是跨分区重命名文件,会有权限问题。

其中此处使用的方案是,先从源文件拷贝到另外分区的目标文件,然后再unlink,就可以了。

转载请注明:在路上 » 【已解决】Node.js中所用的fs.renameSync出错:Error: EXDEV, cross-device link not permitted

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

网友最新评论 (4)

  1. 引用您的方法,运行后报util.pump is not undefined 怎么回事 是不是util没有pump此办法
    榴莲哥11个月前 (12-24)回复
  2. 恩,问题得到解决,牛逼!
    姜炎3年前 (2015-06-12)回复
  3. "util.pump(readStream, writeStream, function() { fs.unlinkSync(files.upload.path); });"编译提示util.pump is deprecated,usereadbleStream.pipe instead. 所以,我的最终是: var readStream = fs.createReadStream(files.upload.path) var writeStream = fs.createWriteStream("/tmp/test.png"); readStream.pipe(writeStream);
    narella4年前 (2014-10-27)回复
18 queries in 0.223 seconds, using 10.25MB memory