Node.js, like other languages, also has file operations. Let’s not talk about the file operations in node.js. File operations in other languages generally include opening, closing, reading, writing, file information, creating and deleting directories, deleting files, detecting file paths, etc. The same is true in node.js. They also have these functions. Maybe the API is different from other languages.
1. Synchronous and asynchronous opening and closing
/** * Created by Administrator on 2016/3/21. */ var fs=require("fs"); //同步读 fs.openSync = function(path, flags, mode) //模块fs.js文件中如上面定义的openSync 函数3个参数 //.1.path 文件路径 //2.flags 打开文件的模式 //3.model 设置文件访问模式 //fd文件描述 var fd=fs.openSync("data/openClose.txt",'w'); //fs.closeSync = function(fd) fs.closeSync(fd); //异步读写 //fs.open = function(path, flags, mode, callback_) //fs.close = function(fd, callback) fs.open("data/openColse1.txt",'w',function(err,fd) { if (!err) { fs.close(fd,function(){ console.log("closed"); }); } });
The flags are also found in other languages. In fact, they are mainly divided into three parts: r, w, and a. They are similar to those in C.
1.r - Open the file in read-only mode, the initial position of the data stream is at the beginning of the file
2.r+ - Open the file in read-write mode, the initial position of the data stream is at the beginning of the file
3.w - If the file exists, the file length will be cleared to 0, that is, the file content will be lost. If it doesn't exist, try to create it. The initial position of the data stream is at the beginning of the file
4.w+ - Open the file in read-write mode. If the file does not exist, try to create it. If the file exists, set the file length to 0, that is, the file content will be lost. The initial position of the data stream is at the beginning of the file
5.a - Open the file in write-only mode. If the file does not exist, try to create it. The initial position of the data stream is at the end of the file. Each subsequent write operation will append the data to the end of the file.
6.a+ - Open the file for reading and writing. If the file does not exist, try to create it. The initial position of the data stream is at the end of the file. Each subsequent write operation will append data to the end of the file.
2. Reading and Writing
1. Simple file reading and writing
/** * Created by Administrator on 2016/3/21. */ var fs = require('fs'); var config = { maxFiles: 20, maxConnections: 15, rootPath: "/webroot" }; var configTxt = JSON.stringify(config); var options = {encoding:'utf8', flag:'w'}; //options 定义字符串编码 打开文件使用的模式 标志的encoding、mode、flag属性 可选 //异步 //fs.writeFile = function(path, data, options, callback_) //同步 //fs.writeFileSync = function(path, data, options) fs.writeFile('data/config.txt', configTxt, options, function(err){ if (err){ console.log("Config Write Failed."); } else { console.log("Config Saved."); readFile(); } }); function readFile() { var fs = require('fs'); var options = {encoding:'utf8', flag:'r'}; //异步 //fs.readFile = function(path, options, callback_) //同步 //fs.readFileSync = function(path, options) fs.readFile('data/config.txt', options, function(err, data){ if (err){ console.log("Failed to open Config File."); } else { console.log("Config Loaded."); var config = JSON.parse(data); console.log("Max Files: " + config.maxFiles); console.log("Max Connections: " + config.maxConnections); console.log("Root Path: " + config.rootPath); } }); }
"C:\Program Files (x86)\JetBrains\WebStorm 11.0.3\bin\runnerw.exe" F:\nodejs\node.exe SimpleReadWrite.js Config Saved. Config Loaded. Max Files: 20 Max Connections: 15 Root Path: /webroot Process finished with exit code 0
2. Synchronous reading and writing
/** * Created by Administrator on 2016/3/21. */ var fs = require('fs'); var veggieTray = ['carrots', 'celery', 'olives']; fd = fs.openSync('data/veggie.txt', 'w'); while (veggieTray.length){ veggie = veggieTray.pop() + " "; //系统api //fd 文件描述 第二个参数是被写入的String或Buffer // offset是第二个参数开始读的索引 null是表示当前索引 //length 写入的字节数 null一直写到数据缓冲区末尾 //position 指定在文件中开始写入的位置 null 文件当前位置 // fs.writeSync(fd, buffer, offset, length[, position]); // fs.writeSync(fd, string[, position[, encoding]]); //fs.writeSync = function(fd, buffer, offset, length, position) var bytes = fs.writeSync(fd, veggie, null, null); console.log("Wrote %s %dbytes", veggie, bytes); } fs.closeSync(fd); var fs = require('fs'); fd = fs.openSync('data/veggie.txt', 'r'); var veggies = ""; do { var buf = new Buffer(5); buf.fill(); //fs.readSync = function(fd, buffer, offset, length, position) var bytes = fs.readSync(fd, buf, null, 5); console.log("read %dbytes", bytes); veggies += buf.toString(); } while (bytes > 0); fs.closeSync(fd); console.log("Veggies: " + veggies);
"C:\Program Files (x86)\JetBrains\WebStorm 11.0.3\bin\runnerw.exe" F:\nodejs\node.exe syncReadWrite.js Wrote olives 7bytes Wrote celery 7bytes Wrote carrots 8bytes read 5bytes read 5bytes read 5bytes read 5bytes read 2bytes read 0bytes Veggies: olives celery carrots Process finished with exit code 0
3. Asynchronous reading and writing and synchronous reading and writing almost have more parameters callback
/** * Created by Administrator on 2016/3/21. */ var fs = require('fs'); var fruitBowl = ['apple', 'orange', 'banana', 'grapes']; function writeFruit(fd){ if (fruitBowl.length){ var fruit = fruitBowl.pop() + " "; // fs.write(fd, buffer, offset, length[, position], callback); // fs.write(fd, string[, position[, encoding]], callback); // fs.write = function(fd, buffer, offset, length, position, callback) fs.write(fd, fruit, null, null, function(err, bytes){ if (err){ console.log("File Write Failed."); } else { console.log("Wrote: %s %dbytes", fruit, bytes); writeFruit(fd); } }); } else { fs.close(fd); ayncRead(); } } fs.open('data/fruit.txt', 'w', function(err, fd){ writeFruit(fd); }); function ayncRead() { var fs = require('fs'); function readFruit(fd, fruits){ var buf = new Buffer(5); buf.fill(); //fs.read = function(fd, buffer, offset, length, position, callback) fs.read(fd, buf, 0, 5, null, function(err, bytes, data){ if ( bytes > 0) { console.log("read %dbytes", bytes); fruits += data; readFruit(fd, fruits); } else { fs.close(fd); console.log ("Fruits: %s", fruits); } }); } fs.open('data/fruit.txt', 'r', function(err, fd){ readFruit(fd, ""); }); }
"C:\Program Files (x86)\JetBrains\WebStorm 11.0.3\bin\runnerw.exe" F:\nodejs\node.exe asyncReadWrite.js Wrote: grapes 7bytes Wrote: banana 7bytes Wrote: orange 7bytes Wrote: apple 6bytes read 5bytes read 5bytes read 5bytes read 5bytes read 5bytes read 2bytes Fruits: grapes banana orange apple Process finished with exit code 0
4. Streaming reading and writing
/** * Created by Administrator on 2016/3/21. */ var fs = require('fs'); var grains = ['wheat', 'rice', 'oats']; var options = { encoding: 'utf8', flag: 'w' }; //从下面的系统api可以看到 createWriteStream 就是创建了一个writable流 //fs.createWriteStream = function(path, options) { // return new WriteStream(path, options); //}; // //util.inherits(WriteStream, Writable); //fs.WriteStream = WriteStream; //function WriteStream(path, options) var fileWriteStream = fs.createWriteStream("data/grains.txt", options); fileWriteStream.on("close", function(){ console.log("File Closed."); //流式读 streamRead(); }); while (grains.length){ var data = grains.pop() + " "; fileWriteStream.write(data); console.log("Wrote: %s", data); } fileWriteStream.end(); //流式读 function streamRead() { var fs = require('fs'); var options = { encoding: 'utf8', flag: 'r' }; //fs.createReadStream = function(path, options) { // return new ReadStream(path, options); //}; // //util.inherits(ReadStream, Readable); //fs.ReadStream = ReadStream; // //function ReadStream(path, options) //createReadStream 就是创建了一个readable流 var fileReadStream = fs.createReadStream("data/grains.txt", options); fileReadStream.on('data', function(chunk) { console.log('Grains: %s', chunk); console.log('Read %d bytes of data.', chunk.length); }); fileReadStream.on("close", function(){ console.log("File Closed."); }); }
"C:\Program Files (x86)\JetBrains\WebStorm 11.0.3\bin\runnerw.exe" F:\nodejs\node.exe StreamReadWrite.js Wrote: oats Wrote: rice Wrote: wheat File Closed. Grains: oats rice wheat Read 16 bytes of data. File Closed. Process finished with exit code 0
Personally, I think these APIs will be ok once you use them and get a feel for them, and you just need to be able to use them when you encounter them.

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.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

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),

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version
Chinese version, very easy to use