denied new File in nodejs nextjs

2jcobegt  于 8个月前  发布在  其他
关注(0)|答案(1)|浏览(151)

尝试在nextjs nodejs中将fs移动到formdata并使用new File

const image = fs.readFileSync(filepath || '');
    const body = new FormData();
    const blob = new Blob([image]);
    const file = new File([blob], originalFilename || '');
    body.append('file', file);

字符串
但得到了这个错误

ReferenceError: File is not defined


我可以在node js中使用new File吗?或者其他解决方案,谢谢。

wh6knrhe

wh6knrhe1#

NodeJS不支持new File()语法,因为它是一个浏览器API。你应该使用filesystem module。下面是一个例子:

const fs = require("fs");

fs.appendFile('example.txt', 'Hello World!', function (err) {
  if (err) throw err;
  console.log('Saved!');
});

字符串
如果您在应用程序中使用async/await语法进行异步操作,则可以像下面的示例中那样使用它:

const fs = require("fs/promises");

const saveFile = async (file, content) => {
  try {
    await fs.appendFile(file, content);
  } catch (err) {
    console.log(err);
  }
}


当然,上面的方法只在服务器端有效,比如在服务器端的action或者路由处理器中,在客户端你仍然可以使用new File()语法。
PS:如果你在Vercel上部署,上面的方法将不起作用,因为他们的文件系统是只读的。

相关问题