简体   繁体   中英

Reading/Writing files in JavaScript

I'm trying to make a web app that will read in a server-side CSV file and display it in a neat, browsable format. The catch is that I want to do it in naked JS/CSS3/HTML5. Is there any way to read and write server-side files with naked JS/CSS3/HTML5? I obviously want this to be OS/browser independent.

What I've tried


I have tried implementing some code I found online (a few sites reference it). Below is what I tried while testing: (I just want the test to show the contents of the webpage, itself, in the webpage)

scriptTest.htm :

<html>
<head>
<script type="text/javascript" src="readIt.JS"></script>
</head>
<body>
<button onclick="return readIt();">Show the code of the page</button>
<div id="readItOutput"></div>
</body>
</html>

readIt.JS :

function readIt()
{
    file = fopen(getScriptPath("scriptTest.htm"), 0);
    file_length = flength(file);
    content = fread(file, file_length);
    document.getElementById("readIt").innerText = content;
}

However, whenever I run it, under Opera and Chrome, it throws the following:

Opera:

Uncaught exception: ReferenceError: Undefined variable: fopen
Error thrown at line 3, column 1 in readIt() in http://s.supuhstar.operaunite.com/s/content/JS/readIt.JS:
    file = fopen(getScriptPath("scriptTest.htm"), 0);
called from line 1, column 0 in <anonymous function>(event) in http://s.supuhstar.operaunite.com/s/content/JS/scripttest.htm:
    return readIt();

Chrome:

Uncaught ReferenceError: getScriptPath is not defined
readItreadIt.JS:3
(anonymous function)scripttest.htm:6
onclick

如果要从服务器编辑一些文件,则需要使用XHR对象将文件下载到客户端,然后再次使用XHR对象将已修改的数据发送回服务器,此外,您还需要服务器上的某种API来发送/接收数据。

File writing cannot be done with JS/CSS3/HTML5 alone for security reasons, otherwise people would be able to modify the js in FireBug and write a file. You would need to create an API of some sort using either server-side JS or a language such as PHP to handle the permissions, file names, file locations, etc…

As for reading, your file would have to be publicly accessible, otherwise you'll need it served by a server-side language such as PHP.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM