Node.js和其他语言一样,也有文件操作。先不说node.js中的文件操作,其他语言的文件操作一般也都是有打开、关闭、读、写、文件信息、新建删除目录、删除文件、检测文件路径等。在node.js中也是一样,也都是这些功能,可能就是api与其他语言不太一样。
一、同步、异步打开关闭
/** * 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"); }); } });
其中的flags其他语言也会有.其实主要分3部分 r、w、a.和C中的差不多。
1.r —— 以只读方式打开文件,数据流的初始位置在文件开始
2.r+ —— 以可读写方式打开文件,数据流的初始位置在文件开始
3.w ——如果文件存在,则将文件长度清0,即该文件内容会丢失。如果不存在,则尝试创建它。数据流的初始位置在文件开始
4.w+ —— 以可读写方式打开文件,如果文件不存在,则尝试创建它,如果文件存在,则将文件长度清0,即该文件内容会丢失。数据流的初始位置在文件开始
5.a —— 以只写方式打开文件,如果文件不存在,则尝试创建它,数据流的初始位置在文件末尾,随后的每次写操作都会将数据追加到文件后面。
6.a+ ——以可读写方式打开文件,如果文件不存在,则尝试创建它,数据流的初始位置在文件末尾,随后的每次写操作都会将数据追加到文件后面。
二、读写
1.简单文件读写
/** * 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.同步读写
/** * 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.异步读写 和同步读写的参数差不多就是多了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.流式读写
/** * 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
个人觉得像这些api用一用感受一下就ok了,遇到了会用就行了。

Vercel是什么?本篇文章带大家了解一下Vercel,并介绍一下在Vercel中部署 Node 服务的方法,希望对大家有所帮助!

gm是基于node.js的图片处理插件,它封装了图片处理工具GraphicsMagick(GM)和ImageMagick(IM),可使用spawn的方式调用。gm插件不是node默认安装的,需执行“npm install gm -S”进行安装才可使用。

如何用pkg打包nodejs可执行文件?下面本篇文章给大家介绍一下使用pkg将Node.js项目打包为可执行文件的方法,希望对大家有所帮助!

本篇文章带大家详解package.json和package-lock.json文件,希望对大家有所帮助!

本篇文章给大家分享一个Nodejs web框架:Fastify,简单介绍一下Fastify支持的特性、Fastify支持的插件以及Fastify的使用方法,希望对大家有所帮助!

node怎么爬取数据?下面本篇文章给大家分享一个node爬虫实例,聊聊利用node抓取小说章节的方法,希望对大家有所帮助!

本篇文章给大家分享一个Node实战,介绍一下使用Node.js和adb怎么开发一个手机备份小工具,希望对大家有所帮助!

先介绍node.js的安装,再介绍使用node.js构建一个简单的web服务器,最后通过一个简单的示例,演示网页与服务器之间的数据交互的实现。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

PhpStorm Mac 版本
最新(2018.2.1 )专业的PHP集成开发工具

Dreamweaver Mac版
视觉化网页开发工具

SecLists
SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

DVWA
Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中

MinGW - 适用于 Windows 的极简 GNU
这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。