【问题】
Win7下,折腾Node.js过程中,运行服务器,其中内部调用相关代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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(); } }); } |
去重命名,结果出错:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | 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?
去试试代码:
1 2 3 4 5 6 7 8 9 10 11 | 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
stream.pipe(res);
。 详见:javascript - Replacing util.pump() in Node.js - Stack Overflow