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.
Re
for
st for /upload received.
About to route a re
for
st for /upload
Request ha
'upload'
pload' was called.
about to parse
pa
done
g done
fs.js:
return
return binding.rename(pathModule._makeLong(oldPath),
^
Error: EXDEV, cross-device link not perm
'C:\Users\CLi\AppData\Local\Temp\df99513a93a1cbfbc26e076f 8ae08b92'
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\formidabl
file
b\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,就可以了。