我正在VUE中编写一个使用“ fs”的项目,这是我的代码。
async Upload(file){
let fs = require('fs');
console.log(file);
console.log(this.dialogImageUrl);
try {
// use 'chunked encoding'
// let stream = fs.createReadStream(this.dialogImageUrl);
// let result = await this.client.putStream(file.file.name, stream);
// console.log(result);
// don't use 'chunked encoding'
let stream = fs.createReadStream('./views/1.txt', {encoding:"utf8"});
let size = fs.statSync('./views/1.txt').size;
let result = await this.client.putStream(
'1', stream, {contentLength: size});
console.log(result);
} catch (e) {
console.log(e);
};
// console.log(file)
}
但是,在使用中遇到以下错误:
TypeError: fs.createReadStream is not a function at _callee3$ (TestViews.vue?6930:97) at tryCatch (runtime.js?96cf:63) at Generator.invoke [as _invoke] (runtime.js?96cf:293) at Generator.eval [as next] (runtime.js?96cf:118) at asyncGeneratorStep (asyncToGenerator.js?1da1:3) at _next (asyncToGenerator.js?1da1:25) at eval (asyncToGenerator.js?1da1:32) at new Promise () at eval (asyncToGenerator.js?1da1:21) at VueComponent.Upload (TestViews.vue?6930:85)
答案 0 :(得分:1)
我假设您的Vue代码正在网络浏览器中运行。网络浏览器中没有fs
模块可用。 fs
是一个Node.js模块,仅在Node.js进程中(在您的服务器或工作站上)可用。
出于安全原因,浏览器中的文件访问受到极大限制。但是,如果您尝试从服务器读取文件,则可以使用ajax来完成,通常(这些天)使用fetch
:
const response = await fetch("./views/1.txt");
if (!response.ok) {
throw new Error("HTTP error " + response.status);
}
const text = await response.text();
// ...use the text here...