search
HomeWeb Front-endJS TutorialJavascript----File operation_javascript skills

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
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
Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use