Can javascript write files

How to read and write files in JavaScript

Are you looking for the ways to access the file system using JavaScript? If your JavaScript code could access local files of the visitor to your site, it would be a huge security problem. That’s why no browsers would allow it.

JavaScript is a simple yet very powerful scripting language. Why not use your knowledge of JavaScript for batch processing of local files and other common tasks?

Well, you can! Not through the Internet of course, but internally on your computer, or on your intranet if you have one.

How can you use JavaScript to access your local files and folders? Currently there are two ways to do it:

1. Using JavaScript extensions (runs from JavaScript Editor), or
2. Using a web page and ActiveX objects (Internet Explorer only)

Using ActiveX objects gives you many possibilities, but there are two distinct disadvantages:

You need a web page to run your JavaScript, and
ActiveX objects only work with the Internet Explorer browser.

When using extensions, all you need to do is select Build / Execute from the menu and let JavaScript Editor do the job.

Example 1 (using extensions): Reading a file

1. Run JavaScript Editor
2. Copy and paste the code below
3. Save the file as FileRead.js, and
4. Select Build / Execute from the menu.

Note: If you do not save the file, getScriptPath() below will return an empty string.

// This example shows file manipulation routines: it echoes
// the contents of itself (the script file).
// Created with Antechinus® JavaScript Editor
// Copyright© 2009 C Point Pty Ltd

fh = fopen(getScriptPath(), 0 ); // Open the file for reading
if (fh!=- 1 ) // If the file has been successfully opened
<
length = flength(fh); // Get the length of the file
str = fread(fh, length); // Read in the entire file
fclose(fh); // Close the file

// Display the contents of the file
write(str);
>

Example 2 (using extensions): Listing files in a folder

1. Run JavaScript Editor
2. Copy and paste the code below
3. Save the file as FolderExample.js, and
4. Select Build / Execute from the menu.

Note: if you do not save the file, getCurrentFolder() below will return an empty string.

// This example shows folder manipulation routines: it lists
// the contents of the current folder.
// Created with Antechinus® JavaScript Editor
// Copyright© 2009 C Point Pty Ltd

write( «The contents of » + getCurrentFolder());

fileName = findFirstFile( «*.*» ); // Find the first file matching the filter
while (fileName.length)
<
write(fileName);
fileName = findNextFile(); &nbsp // Find the next file matching the filter
>

Example 3 (using extensions): Writing a file using JavaScript

Writing files using JavaScript and built-in extensions is straightforward: open the file for writing, write to a file and close a file.

1. Run JavaScript Editor
2. Copy and paste the code below
3. (Optional) Save the file as WriteFileExample.js, and
4. Select Build / Execute from the menu.

var fh = fopen( «c:\\MyFile.txt», 3); // Open the file for writing

if (fh!= -1 ) // If the file has been successfully opened
var str = «Some text goes here. «;
fwrite(fh, str); // Write the string to a file
fclose(fh); // Close the file
>

Читайте также:  Python типы данных type

Example 4 (using ActiveX and a web page): Listing available drives

1. Run JavaScript Editor
2. Copy and paste the code below
3. Save the file as DriveList.htm, and
4. View the page using Internal Viewer or Internet Explorer

function ShowAvailableDrives()
<
document.write(GetDriveList());
>

function GetDriveList()
<
var fso, s, n, e, x;
fso = new ActiveXObject( «Scripting.FileSystemObject» );
e = new Enumerator(fso.Drives);
s = «» ;
do
<
x = e.item();
s = s + x.DriveLetter;
s += «:- » ;
if (x.DriveType == 3 ) n = x.ShareName;
else if (x.IsReady) n = x.VolumeName;
else n = «[Drive not ready]» ;
s += n + «
» ;
e.moveNext();
> while (!e.atEnd());

Example 5 (using ActiveX and a web page): Writing a file using JavaScript

Writing files via ActiveX is slightly more involved than using JavaScript Editor extensions: you create an instance of a FileSystemObject, create a file, write to it, and close it.

In addition, you cannot run the code on its own, it needs to be a part of a web page or a stand-alone HTML Application (HTA).

1. Run JavaScript Editor
2. Copy and paste the code below
3. Save the file as WriteFileX.htm, and
4. View the page using Internal Viewer or Internet Explorer

function WriteFile()
<
var fso = new ActiveXObject( «Scripting.FileSystemObject» );
var fh = fso.CreateTextFile( «c:\\Test.txt» , true );
fh.WriteLine( «Some text goes here. » );
fh.Close();
>

Use JavaScript for batch processing and common tasks of your local/intranet files
Using ActiveX objects works well, but you need a web page to run your JavaScript
ActiveX objects work on Internet Explorer, but not on Opera, Netscape or Firefox
When using JavaScript extensions you do not need a web page: run your code straight from the JavaScript Editor.

New to JavaScript? Become an expert in record time with the JavaScript Editor’s step-by-step tutorials full of examples you can copy, paste and run. Also available: online version of the JavaScript tutorials.
Already an expert? Spice up your web pages with Antechinus® JavaScript Editor — effortlessly add multilevel menus, effects, Multimedia capabilities and e-Commerce.

Copyright © 1998- C Point Pty Ltd. All Rights Reserved.

Источник

JavaScript Read and Write to Text File

In this tutorial, I will tell you about how you can read and write to text file using JavaScript. As we know JavaScript does not have the ability to access the user’s file system so for this we need to run the project on a server. To implement this we use node.js.

In node.js these are one library fs (File-System) which is used to manage all read and write operations. By using the fs module we can read and write files in both synchronous and asynchronous way.

There are many ways in which we can read and write data to file. Lets have a look on each of them one by one.

JavaScript Read and Write to Text File

Method 1: Using Node.js

First is by using writefile and readFile method in node.js environment.

Читайте также:  Php получить время часы

This is used to write content to file. Its syntax is below:

It has three parameters path, data, callback.

Path: The path is the location of Text File. If the file is to be generated in the same folder as that of the program, then provide the name of the file only. If the file does not exist then the new file will be created automatically.

Data: Second is Data in This parameter we need to pass info that is required to write in the file.

Callback: Last one is the Callback Function in this we pass error string. If the operation fails to write the data, an error shows the fault.

To run above code run this command:

>node index.js

It is used to read the content of the file. its syntax is:

It also has three parameters path, callback, options.

path is a location of Text File. If both file and program are in a similar folder, then directly give the file name of the text file.

Second option which specifies the data is to be gathered from the file and it is optional. If you pass nothing then it returns raw buffer.

The last one is Callback function which has two more parameters (error, txtString). If at any instance it fails to load or read the file then it returns error or exception otherwise it returns all data of the file.

To run this program enter below command:

>node index.js

Method 2: Using ActiveXObject

Another method is by using a web page ActiveX objects but this method is mainly work in Internet Explorer only.

This ActiveXObject is used to return an instance of a file system library which is used with the CreateTextFile method. This JS method which generates a file defined functions and states a TextStream object to read from or write to the file. It also returns a boolean value on the basis of this we can find out that we can overwrite to the current file or not. So, if you want to add the data to the created file you can use writeline method which is used to add text string to the file.

Using ActiveX objects, the following should be included in your code to read a file:

The ActiveX object contains three things libraryname, classname, location. So, classname is the instance of a class that needs to be created. libraryname is a mandatory field and it is the sign of the app giving the object.

To open a new file:

Источник

How to Write to a File Using JavaScript, With Examples

Write to File in JavaScript

This article will show you how to write to files from JavaScript – both from the web browser and Node.js environments. With examples on how to write, append, update, delete and rename files.

JavaScript code is usually run from one of two environments – within a web browser when viewing a web page or in a Node.js environment which allows JavaScript to be executed outside of a web browser – commonly used for building back-end services and web apps.

Write to a File From the Browser with JavaScript

First, how to do it from the browser. Modern JavaScript includes built-in tools for this. The steps are as follows:

  • Create a file using the JavaScript Blob object to represent the file
  • Create a URL for the new object
  • Provide a link which the user can click to tell the browser to download the Blob object from the URL as a file
Читайте также:  Открыть xlsx python pandas

The user can then click the link, and they will be presented with the standard save dialog from their web browser, allowing them to save the generated file wherever they wish.

Here’s how the code looks as a re-usable function you can copy and paste to use yourself:

// A global variable should be defined to hold the URL for the file to be downloaded // This is good practice as if many links are being generated or the link is being regularly updated, you don't want to be creating new variables every time, wasting memory var textFileUrl = null; // Function for generating a text file URL containing given text function generateTextFileUrl(txt) < let fileData = new Blob([txt], ); // If a file has been previously generated, revoke the existing URL if (textFileUrl !== null) < window.URL.revokeObjectURL(textFile); >textFileUrl = window.URL.createObjectURL(fileData); // Returns a reference to the global variable holding the URL // Again, this is better than generating and returning the URL itself from the function as it will eat memory if the file contents are large or regularly changing return textFileUrl; >; // Generate the file download URL and assign it to the link // Wait until the page has loaded! Otherwise the download link element will not exist window.addEventListener("load", function()< document.getElementById('downloadLink').href = generateTextFileUrl('Hello world!'); >);

You’ll need the following link in your HTML to display a download button:

This solution does not attempt to emulate clicking on the generated links or any of that nonsense. Browsers will usually block it, and you shouldn’t be trying to sneak downloads past a user without them expressly clicking a link to save the file themselves anyway.

Write to a File From Node.js

If you’re working in a Node.js environment, all of the tools for managing files are available in the built-in fs library.

Reading or writing files takes time and can halt execution. Previously, it was best to use callbacks to perform file operations once a file has been successfully read or written to.

Now, however, Promises provide a standardized approach for asynchronous tasks. So these examples will use Promises instead of callbacks to keep things modern.

Here’s how to write a text file from Node.js:

// Import the promise-based version of the fs library const fs = require('fs').promises; // Define some text to be written to a file var textData = "Hello world!"; try < // Write text to the given file name // await tells JavaScript to wait for the asyncronous function (Promise) to resolve before continuing await fs.writeFile('myFile.txt', textData); >catch (error) < // Output any errors for inspection console.log(error); >

Appending to a File from Node.js

Following on from above, it’s simple to use the fs library to append data to a file:

const fs = require(‘fs’).promises; try < await fs.appendFile('myFile.txt', textData); >catch (error)

Updating a File

To update a file, you can either append to it using appendFile or overwrite it using writeFile, as outlined above.

Renaming a File

const fs = require(‘fs’).promises; try < await fs.rename('oldFileName.txt', 'newFileName.txt'); >catch (error)

Deleting a File

const fs = require(‘fs’).promises; try < await fs.unlink('myFile.txt'); >catch (error)

Источник

Оцените статью