一切福田,不離方寸,從心而覓,感無不通。

Node.js中所用的fs.renameSync出错:Error: EXDEV, cross-device link no

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.
Reforst for /upload received.
About to route a reforst for /upload
Request ha'upload'pload' was called.
about to parse
padoneg done
 
fs.js:returnreturn binding.rename(pathModule._makeLong(oldPath),
                 ^
Error: EXDEV, cross-device link not perm'C:\Users\CLi\AppData\Local\Temp\df99513a93a1cbfbc26e076f8ae08b92'08b92'
    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\formidablfileb\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,就可以了。

转自:http://blog.sina.com.cn/s/blog_6f0e38af0101dp2g.html