2

How can I write and read a text file with JavaScript?

1
  • 1
    You'll need to provide more context. In a web browser? (You can't.) In the Windows shell? (Use the FileSystemObject.) In some other environment? Commented Dec 12, 2009 at 9:22

6 Answers 6

6

You need to run the JS in a host environment that provides an API for accessing the file system.

If you are on Windows, then you can use WSH to achieve this.

JS running a browser, under normal security conditions, cannot access the file system.

Sign up to request clarification or add additional context in comments.

Comments

6

If you are using Firefox, this may help.

//Your text file location on system
var savefile = "c:\\yourtextfile.txt"; 
try {
    netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");

    var file = Components.classes["@mozilla.org/file/local;1"]
    .createInstance(Components.interfaces.nsILocalFile);
file.initWithPath( savefile );
if ( file.exists() == false ) {
    alert( "Creating file... " );
    file.create( Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 420 );
}

var outputStream = Components.classes["@mozilla.org/network/file-output-stream;1"]
    .createInstance( Components.interfaces.nsIFileOutputStream );

outputStream.init( file, 0x04 | 0x08 | 0x20, 420, 0 );
var output = "Your text here";
var result = outputStream.write( output, output.length );
outputStream.close();

alert("Done");
} 
catch (e) {
    alert("Some error occured");
}

It worked for me, hope works for you as well :)

1 Comment

Works for me. Thanks. Does Chrome have this capability?
4

You can't. JavaScript in the browser has no access to the user's filesystem, by design.

Comments

2

there is an interesting script, in case you are willing to use greasemonkey:

// ==UserScript==
// @name           Store notes for every website
// @creator        Xavi Esteve
// @namespace      http://www.xaviesteve.com
// @description    Shows a little notebook at the right bottom of every page that stores any text you type in automatically. Each domain has his separate notebook which can be shown/hidden with a click. 
// @version        1.3
// @include        *
// @exclude        http*://*.google.*/mail/*
// @exclude        http*://*.googlemail.*
// @exclude        file:///*
// ==/UserScript==

if (self == top) {

// VARIABLES
var e = document.domain.split(/\./);
gdomain = document.domain;
var gotit = GM_getValue(gdomain, '[Type notes for '+gdomain+']');
// FUNCTIONS
function saveit() {
  GM_setValue(gdomain, document.getElementById('gm_textarea').value);
  return false;
}
/* Insert HTML */
/* div */
var div = document.createElement('div');
div.innerHTML = '<a onmousedown="var tbh = document.getElementById(\'gm_tobehiden\');if(tbh.style.display==\'none\'){tbh.style.display=\'block\';document.getElementById(\'gm_textarea\').focus();}else{tbh.style.display = \'none\';}return false;" title="Notebook">'+gdomain+'</a><div id="gm_tobehiden"><div id="gm_title"></div></div>';
div.id = "gm_notebook";
document.body.insertBefore(div, document.body.lastChild);
/*  textarea */
var textarea = document.createElement('textarea');
textarea.appendChild(document.createTextNode(gotit));
textarea.addEventListener('keyup', saveit, false);
textarea.addEventListener('click', saveit, false);
textarea.id = "gm_textarea";
var gm_title = document.getElementById('gm_title');
gm_title.parentNode.insertBefore(textarea, gm_title.nextSibling);
/* Insert CSS */
  var menuCode = new Array();
  menuCode.push("#gm_notebook {-moz-opacity:0.9;position:fixed;bottom:40px;right:5px;border:1px solid #ccc;font-size:10px;color:#333;background:#f1f1f1;padding:3px 5px 5px 5px;font-family:Arial,sans-serif}#gm_notebook a {color:#0085d5;margin:2px;cursor:pointer}");
  menuCode.push("#gm_tobehiden {display:none;width:200px;height:300px;padding:5px}");  // Change display to block to show the notebook by default 
  menuCode.push("#gm_textarea {width:100%;height:100%;color:#000;font-family:monospace}");
  var style = document.createElement('style');
  style.type = 'text/css';
  style.innerHTML = menuCode.join('');
  menuCode.length = 0;

  try { document.getElementsByTagName('head')[0].appendChild(style); }
  catch(e) {}

}

Comments

0

You can not access your file system with Java Script, so unfortunately you can't

4 Comments

In a web browser. JavaScript isn't limited to web browsers.
@Crowder: Technically you are right, but I would assume it de facto unless explicitly specified otherwise. I would assume a .NET application is running on Windows unless you tell me it is running on Mono.
@dnl.vssll: Never assume, it makes an "ass" out of "u" and "me".
To further my comment, JavaScript is used very popularly in MANY more places than the web, desktop widgets and shell scripts are just some examples. In all fairness, it's the asker's fault for not being more specific with his/her question.
0

In FF 3.6 it is possible, see my technical example at http://www.bruechner.de/md5file/js/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.