fs.renameSync()运行时报错

初学node.js,跟着node入门,操作了一遍。在最后一步,上传图片并显示时遇到报错

fs.js:115
throw err;
^
Error: ENOENT: no such file or directory, rename 'C:\Users\catcher\AppData\Local\Temp\upload_16f7bede547980c767e1e031a3720f67' -> '/tmp/test.png'
at Object.renameSync (fs.js:594:3)
at C:\IdeaProjects\nodejs\requestHandlers.js:34:8
at IncomingForm. (C:\IdeaProjects\nodejs\node_modules\formidable\lib\incoming_form.js:107:9)
at IncomingForm.emit (events.js:182:13)
at IncomingForm._maybeEnd (C:\IdeaProjects\nodejs\node_modules\formidable\lib\incoming_form.js:557:8)
at C:\IdeaProjects\nodejs\node_modules\formidable\lib\incoming_form.js:238:12
at WriteStream. (C:\IdeaProjects\nodejs\node_modules\formidable\lib\file.js:79:5)
at Object.onceWrapper (events.js:273:13)
at WriteStream.emit (events.js:182:13)
at finishMaybe (_stream_writable.js:641:14)

根据报错信息,查找到相应的代码,
fs.renameSync(files.upload.path, "/tmp/test.png");

首先想到的是代码中是相对路径,导致不能查找到文件所在的位置,于是将路径补全

fs.renameSync(files.upload.path, "C:/IdeaProjects/nodejs/tmp/test.png");

还是同样的报错

Error: ENOENT: no such file or directory, rename 'C:\Users\catcher\AppData
\Local\Temp\upload_cb107f6decde929aff2b86f5bfb3a330' -> 'C:/IdeaProjects/
nodejs/tmp/test.png'

仔细观察后发现在路径名中的左右反斜杠的问题。即在windows中路径名间隔符为右反斜杠'',而在Linux和mac os中都是左反斜杠'/'。于是修改代码为
fs.renameSync(files.upload.path, "C:\IdeaProjects\nodejs\tmp\test.png");
依然报错

Error: ENOENT: no such file or directory, rename 'C:\Users\catcher\AppData
\Local\Temp\upload_5b3fdf35fbb17a8579b5c2245f070543' -> 'C:IdeaProjects
odejs mp est.png'

问题在于右反斜杠是转义字符,所以路径名称应该为
fs.renameSync(files.upload.path, "C:\\IdeaProjects\\nodejs\\tmp\\test.png");
遗憾的是依然报错,

Error: ENOENT: no such file or directory, rename 'C:\Users\catcher\AppData
\Local\Temp\upload_d3cceb8f8c01ae2a796d1f356e91ae0f' -> 'C:\IdeaProjects
\nodejs\tmp\test.png'

不过显示的路径算是对了。
再次阅读报错信息后 no such file or directory ,会不会是文件夹tmp需要手动创建?(没错,我以为该方法会自动创建不存在的文件夹,所以在一开始我还尝试通过everything去查找tmp文件夹)自己创建文件夹tmp之后,成功上传图片并预览。
而之前反复改动的文件路径,以下三种方式亲测可用:

fs.renameSync(files.upload.path, "./tmp/test.png"); //注意点号

fs.renameSync(files.upload.path, "C:\\IdeaProjects\\nodejs\\tmp\\test.png");

fs.renameSync(files.upload.path, "C:/IdeaProjects/nodejs/tmp/test.png");

附:在网上查询资料,提到fs.renameSync() 不允许跨分区移动文件。解决办法如下:
https://stackoverflow.com/questions/4568689/how-do-i-move-file-a-to-a-different-partition-or-device-in-node-js

var fs = require('fs');
//var util = require('util');
var is = fs.createReadStream('source_file');
var os = fs.createWriteStream('destination_file');
is.pipe(os);
is.on('end',function() {
    fs.unlinkSync('source_file');
});
/* node.js 0.6 and earlier you can use util.pump:
util.pump(is, os, function() {
    fs.unlinkSync('source_file');
});
*/

你可能感兴趣的:(fs.renameSync()运行时报错)