How to read and write into file using JavaScript?

后端 未结 17 2478
孤街浪徒
孤街浪徒 2020-11-22 02:00

Can anybody give some sample code to read and write a file using JavaScript?

相关标签:
17条回答
  • 2020-11-22 02:41

    If you are using JScript (Microsoft's Javascript) to do local scripting using WSH (NOT in a browser!) you can use Scripting.FileSystemObject to access the file system.

    I think you can access that same object in IE if you turn a lot of security settings off, but that would be a very, very bad idea.

    MSDN here

    0 讨论(0)
  • 2020-11-22 02:41

    You cannot do file i/o on the client side using javascript as that would be a security risk. You'd either have to get them to download and run an exe, or if the file is on your server, use AJAX and a server-side language such as PHP to do the i/o on serverside

    0 讨论(0)
  • 2020-11-22 02:43

    No. Browser-side javascript doesn't have permission to write to the client machine without a lot of security options having to be disabled

    0 讨论(0)
  • 2020-11-22 02:45

    Writing this answer for people who wants to get a file to download with specific content from javascript. I was struggling with the same thing.

    const data = {name: 'Ronn', age: 27};              //sample json
    const a = document.createElement('a');
    const blob = new Blob([JSON.stringify(data)]);
    a.href = URL.createObjectURL(blob);
    a.download = 'sample-profile';                     //filename to download
    a.click();
    

    Check Blob documentation here - Blob MDN

    0 讨论(0)
  • 2020-11-22 02:47

    Here is write solution for chrome v52+ (user still need to select a destination doe...)
    source: StreamSaver.js

    <!-- load StreamSaver.js before streams polyfill to detect support -->
    <script src="StreamSaver.js"></script>
    <script src="https://wzrd.in/standalone/web-streams-polyfill@latest"></script>
    
    const writeStream = streamSaver.createWriteStream('filename.txt')
    const encoder = new TextEncoder
    let data = 'a'.repeat(1024)
    let uint8array = encoder.encode(data + "\n\n")
    
    writeStream.write(uint8array) // must be uInt8array
    writeStream.close()
    

    Best suited for writing large data generated on client side.
    Otherwise I suggest using FileSaver.js to save Blob/Files

    0 讨论(0)
提交回复
热议问题