简体   繁体   中英

How do I read a txt file in javascript

I'm looking for some simple code to read a txt file using JavaScript. First choice would be record by record, but if it is in an array that is fine too

The JavaScript standard library does not include any general I/O operations, so reading a file must be delegated to some other library provided by your environment.

For example, if you are targeting a web platform you could make the text file available from the web server and fetch it via an XMLHttpRequest. Parsing the file would be up to you entirely using things like String slicing and regular expressions.

If you are targeting a "server" platform using node.js or Rhino then you can use the I/O facilities provided with those environments, eg the node.js FileSystem interface and readFile(filename) (or Java's FileReader ), respectively. Other JavaScript/ECMAScript platforms will likely provide their own utilities for accessing the filesystem.

If you mean on the local computer, that's not possible if you're talking about web scripting, which I would assume you are (if you're talking about using the WSH or something then you create a FileSystemObject, but that's probably not what you want). If you mean read a file from the server, you would use Ajax:

function readText(url) {
    var rq = new XMLHttpRequest();

    rq.open('GET', url, false);
    rq.send(null);

    if (rq.status >= 200 && rq.status < 400) {
        return rq.responseText;
    }

    throw new Error("Couldn't read the requested file; status = " + rq.status.toString());
}

And call readText with the URL of the file to read.

JavaScript DOES provide an interface for reading files. It's the FileReader API. You can setup an <input type="file"> for the user to select a file from their machine, then use .readAsText() . See http://www.html5rocks.com/en/tutorials/file/dndfiles/

这将是一个安全问题,并且高度怀疑JavaScript是否可以访问用户的硬盘驱动器。

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