Home Web Front-end JS Tutorial Javascript----File operation_javascript skills

Javascript----File operation_javascript skills

May 16, 2016 pm 07:20 PM

Javascript----File Operation
1. Functional Implementation Core: FileSystemObject Object
To implement the file operation function in JavaScript, we mainly rely on the FileSystemobject object.
2. FileSystemObject Programming
Programming using the FileSystemObject object is very simple. Generally, you need to go through the following steps: Create a FileSystemObject object, apply related methods, and access object-related properties.
(1) Create a FileSystemObject object
The code to create a FileSystemObject object only needs one line:
var fso = new ActiveXObject("Scripting.FileSystemObject");
After the above code is executed, fso becomes a FileSystemObject Object instance.
(2) Apply related methods
After creating an object instance, you can use the related methods of the object. For example, use the CreateTextFile method to create a text file:
var fso = new ActiveXObject("Scripting.FileSystemObject");
var f1 = fso.createtextfile("c:\myjstest.txt",true");
(3) Accessing object-related attributes
To access object-related attributes, you must first establish a handle to the object, which is achieved through the get series of methods: GetDrive is responsible for obtaining drive information, GetFolder is responsible for obtaining folder information, GetFile Responsible for obtaining file information. For example, after pointing to the following code, f1 becomes the handle pointing to the file c:test.txt:
var fso = new ActiveXObject("Scripting.FileSystemObject");
var f1 = fso. GetFile("c:\myjstest.txt");
Then, use f1 to access the related properties of the object. For example:
var fso = new ActiveXObject("Scripting.FileSystemObject");
var f1 = fso. .GetFile("c:\myjstest.txt");
alert("File last modified: " f1.DateLastModified);
After executing the last sentence above, the last modified date attribute of c:myjstest.txt will be displayed Value.
But please note one thing: for objects created using the create method, you no longer need to use the get method to obtain the object handle. In this case, you can directly use the handle name created by the create method:
var fso = new ActiveXObject("Scripting.FileSystemObject");
var f1 = fso.createtextfile("c:\myjstest.txt",true");
alert("File last modified: " f1.DateLastModified);
3. Operating drives (Drives)
It is easy to use FileSystemObject objects to programmatically operate drives (Drives) and folders (Folders), just like interacting with files in the Windows file browser, such as: copy, Move a folder and get the properties of the folder.
(1) Drives object attributes
The Drive object is responsible for collecting the physical or logical drive resource content in the system. It has the following attributes:
l TotalSize: The drive size calculated in bytes.
l AvailableSpace or FreeSpace: The available space of the drive calculated in bytes.
l DriveLetter: drive letter.
l DriveType: Drive type, the value is: removable (removable media), fixed (fixed media), network (network resource), CD-ROM or RAM disk.
l SerialNumber: The serial number of the drive.
l FileSystem: The file system type of the drive, the values ​​are FAT, FAT32 and NTFS.
l IsReady: Whether the drive is available.
l ShareName: Share name.
l VolumeName: Volume name.
l Path and RootFolder: The path or root directory name of the drive.
(2) Drive object operation routine
The following routine displays the volume label, total capacity and available space of drive C:
var fso, drv, s ="";
fso = new ActiveXObject("Scripting.FileSystemObject");
drv = fso.GetDrive(fso.GetDriveName("c:\"));
s = "Drive C:" " - ";
s = drv.VolumeName "n";
s = "Total Space: " drv.TotalSize / 1024;
s = "Kb" "n";
s = "Free Space: " drv.FreeSpace / 1024;
s = "Kb" "n";
alert(s);
4. Operation folders (Folders)
Operations involving folders include creation, movement, deletion and acquisition Related properties.
Folder object operation routine:
The following routine will practice operations such as obtaining the name of the parent folder, creating a folder, deleting a folder, and determining whether it is the root directory:
var fso, fldr, s = "";
// Create FileSystemObject object instance
fso = new ActiveXObject("Scripting.FileSystemObject");
// Get Drive object
fldr = fso.GetFolder("c:\") ;
// Display the name of the parent directory
alert("Parent folder name is: " fldr "n");
// Display the name of the drive
alert("Contained on drive " fldr.Drive "n");
// Determine whether it is the root directory
if (fldr.IsRootFolder)
alert("This is the root folder.");
else
alert("This folder isn't a root folder.");
alert("nn");
// Create a new folder
fso.CreateFolder ("C:\Bogus");
alert( "Created folder C:\Bogus" "n");
// Display the folder base name, excluding the path name
alert("Basename = " fso.GetBaseName("c:\bogus") "n ");
//Delete the created folder
fso.DeleteFolder ("C:\Bogus");
alert("Deleted folder C:\Bogus" "n");
5 , operating files (Files)
The operations on files are more complicated than the drive (Drive) and folder (Folder) operations introduced above. They are basically divided into the following two categories: creating, copying, and moving files. , deletion operations and creation, addition, deletion and reading operations on file content. Each is introduced in detail below.
(1) Create a file
There are 3 methods to create an empty text file, which is sometimes called a text stream.
The first is to use the CreateTextFile method. The code is as follows:
var fso, f1;
fso = new ActiveXObject("Scripting.FileSystemObject");
f1 = fso.CreateTextFile("c:\testfile.txt", true);
The second method is to use the OpenTextFile method and add the ForWriting attribute. The value of ForWriting is 2. The code is as follows:
var fso, ts;
var ForWriting= 2;
fso = new ActiveXObject("Scripting.FileSystemObject");
ts = fso.OpenTextFile("c:\test.txt ", ForWriting, true);
The third method is to use the OpenAsTextStream method, and also set the ForWriting attribute. The code is as follows:
var fso, f1, ts;
var ForWriting = 2;
fso = new ActiveXObject("Scripting.FileSystemObject");
fso.CreateTextFile ("c:\test1.txt ");
f1 = fso.GetFile("c:\test1.txt");
ts = f1.OpenAsTextStream(ForWriting, true);
(2) Add data to the file
When After the file is created, you generally need to follow the steps of "open file -> fill in data -> close file" to add data to the file.
To open a file, you can use the OpenTextFile method of the FileSystemObject object, or the OpenAsTextStream method of the File object.
To fill in data, use the Write, WriteLine or WriteBlankLines method of the TextStream object. Under the same function of writing data, the difference between these three methods is that the Write method does not add a new line break at the end of the written data, the WriteLine method adds a new line break at the end, and WriteBlankLines adds one or more blanks. OK.
To close the file, you can use the Close method of the TextStream object.
(3) Routines for creating files and adding data
The following code combines the steps of creating files, adding data, and closing files:
var fso, tf;
fso = new ActiveXObject("Scripting.FileSystemObject");
// Create a new file
tf = fso.CreateTextFile("c:\testfile.txt", true);
// Fill in the data and add a newline character
tf.WriteLine("Testing 1, 2, 3.") ;
// Add 3 blank lines
tf.WriteBlankLines(3) ;
// Fill in one line without newlines
tf.Write ("This is a test.");
//Close the file
tf.Close();
(4) Read the file content
Read from the text file To get data, use the Read, ReadLine or ReadAll method of the TextStream object. The Read method is used to read a specified number of characters in the file; the ReadLine method reads an entire line, excluding newlines; and the ReadAll method reads the entire content of the text file. The read content is stored in a string variable for display and analysis. When using the Read or ReadLine method to read the file content, if you want to skip some parts, you must use the Skip or SkipLine method.
다음 코드는 파일을 열고 데이터를 채운 다음 데이터를 읽는 방법을 보여줍니다.
var fso, f1, ts, s
var ForReading = 1
fso = new ActiveXObject( "Scripting.FileSystemObject ");
// 파일 생성
f1 = fso.CreateTextFile("c:\testfile.txt", true)
// 데이터 한 줄 채우기
f1.WriteLine("Hello World" );
f1.WriteBlankLines(1);
// 파일 닫기
f1.Close()
// 파일 열기
ts = fso.OpenTextFile("c:\testfile.txt", ForReading);
// 파일 내용을 문자열로 읽습니다.
s = ts.ReadLine()
// 문자열 정보 표시
alert("파일 내용 = '" s "'");
//파일 닫기
ts.Close()
(5) 파일 이동, 복사 및 삭제
위의 세 가지 파일 작업에는 두 가지 해당 메서드가 있습니다. File.Move 또는 FileSystemObject.MoveFile은 파일을 이동하는 데 사용되며 File.Delete 또는 FileSystemObject.DeleteFile은 파일을 삭제하는 데 사용됩니다. 파일.
다음 코드는 C 드라이브의 루트 디렉터리에 텍스트 파일을 만들고 일부 내용을 채운 다음 파일을 tmp 디렉터리로 이동하고 temp 디렉터리 아래에 파일 복사본을 만들고 마지막으로 파일을 삭제하는 방법을 보여줍니다. :
var fso, f1, f2, s;
fso = new ActiveXObject("Scripting.FileSystemObject")
f1 = fso.CreateTextFile("c:\testfile.txt", true);
// 한 줄 작성
f1.Write("테스트입니다.")
// 파일 닫기
f1.Close()// Get C: 루트 디렉터리 파일 핸들
f2 = fso.GetFile("c:\testfile.txt")
// 파일을 mp 디렉터리로 이동합니다.
f2.Move("c:\tmp \testfile.txt") ;
//emp 디렉터리에 파일을 복사합니다
f2.Copy ("c:\temp\testfile.txt");
// 파일 핸들 가져오기
f2 = fso.GetFile("c :\tmp\testfile.txt");
f3 = fso.GetFile("c:\temp\testfile.txt")
// 파일 삭제
f2 .Delete();
f3.Delete();
6. 결론
위의 소개와 FileSystemObject의 다양한 객체, 속성 및 메소드의 예를 통해 여러분은 이미 JavaScript 언어를 사용하는 방법을 알고 계실 것입니다. 페이지의 드라이브, 파일 및 파일을 작동하는 방법을 명확하게 이해했습니다. 그러나 위에서 언급한 루틴은 매우 간단하며 JavaScript 파일 조작 기술을 완전하고 유연하게 익히려면 많은 실습이 필요합니다. 그리고 한 가지 더 알려드릴 점은, 브라우저에서 파일을 읽고 쓰는 등의 고급 작업이 포함되기 때문에 기본 브라우저 보안 수준의 경우 코드가 실행되기 전에 정보 프롬프트가 표시된다는 점입니다. 실제 환경에서 이를 확인하세요. 방문자에게 주의를 기울이도록 유도합니다.

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

TypeScript for Beginners, Part 2: Basic Data Types TypeScript for Beginners, Part 2: Basic Data Types Mar 19, 2025 am 09:10 AM

Once you have mastered the entry-level TypeScript tutorial, you should be able to write your own code in an IDE that supports TypeScript and compile it into JavaScript. This tutorial will dive into various data types in TypeScript. JavaScript has seven data types: Null, Undefined, Boolean, Number, String, Symbol (introduced by ES6) and Object. TypeScript defines more types on this basis, and this tutorial will cover all of them in detail. Null data type Like JavaScript, null in TypeScript

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

Can PowerPoint run JavaScript? Can PowerPoint run JavaScript? Apr 01, 2025 pm 05:17 PM

JavaScript can be run in PowerPoint, and can be implemented by calling external JavaScript files or embedding HTML files through VBA. 1. To use VBA to call JavaScript files, you need to enable macros and have VBA programming knowledge. 2. Embed HTML files containing JavaScript, which are simple and easy to use but are subject to security restrictions. Advantages include extended functions and flexibility, while disadvantages involve security, compatibility and complexity. In practice, attention should be paid to security, compatibility, performance and user experience.

See all articles