mouren Zhu
mouren Zhu

Reputation: 11

TypeError: fs.createReadStream is not a function?

I'm writing a project in VUE that uses 'fs', and here's my code.

 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)
        }

However, the following error was encountered in use:

 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)

Upvotes: 1

Views: 3902

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075199

I assume your Vue code is running in a web browser. There is no fs module available in web browsers. fs is a Node.js module, which is only available in a Node.js process (on your server or workstation).

File access on browsers is extremely limited for security reasons. But if you're trying to read a file from your server, you can do that with ajax, typically (these days) using 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...

Upvotes: 2

Related Questions