将文件写入子目录node.js

Write file to a subdirectory node.js

本文关键字:node js 子目录 文件      更新时间:2023-09-26

我正在使用node和express,我有一个类似的目录结构

public
   img
   css
   js
server.js

在server.js中,我有以下代码用于写入png文件

fs.writeFile('testfile.png', imageData, function(err){
        res.send("file successfully created");
    });

这将在根目录中创建文件,即具有以下目录结构

public
   img
   css
   js
server.js
testfile.png

如何在img目录中创建testfile.png?简单地使用img/testfile.png/img/testfile.png/public/img/testfile.png是不起作用的——不会创建任何文件。

感谢帮助!

您可以执行此

'./public/img/testfile.png'

或者,你可以给出像这样的相对路径

__dirname + '/public/img/testfile.png'

还要检查目录img的权限。可能是没有给予写入权限。