Node.js 文件系统
2016-02-29 10:50
519 查看
无标题
Node.js 提供一组类似 UNIX(POSIX)标准的文件操作API。 Node 导入文件系统模块(fs)语法如下所示:
[/code]
异步的方法函数最后一个参数为回调函数,回调函数的第一个参数包含了错误信息(error)。
建议大家是用异步方法,比起同步,异步方法性能更高,速度更快,而且没有阻塞。
As an asynchronous event driven framework, Node.js is designed to build scalable network applications. In the following "hello world" example, many connections can be handled concurrently. Upon each connection the callback is fired, but if there is no work to be done Node is sleeping.
const http = require('http');
创建 file.js 文件, 代码如下:
[/code]
Node.js 提供一组类似 UNIX(POSIX)标准的文件操作API。 Node 导入文件系统模块(fs)语法如下所示:
var fs = require("fs")
[/code]
异步和同步
Node.js 文件系统(fs 模块)模块中的方法均有异步和同步版本,例如读取文件内容的函数有异步的 fs.readFile() 和同步的 fs.readFileSync()。异步的方法函数最后一个参数为回调函数,回调函数的第一个参数包含了错误信息(error)。
建议大家是用异步方法,比起同步,异步方法性能更高,速度更快,而且没有阻塞。
实例
创建 input.txt 文件,内容如下:About Node.js?As an asynchronous event driven framework, Node.js is designed to build scalable network applications. In the following "hello world" example, many connections can be handled concurrently. Upon each connection the callback is fired, but if there is no work to be done Node is sleeping.
const http = require('http');
创建 file.js 文件, 代码如下:
var fs = require("fs");// 异步读取
fs.readFile('input.txt', function (err, data) {if (err) {return console.error(err);}
console.log("异步读取: " + data.toString());});// 同步读取var data = fs.readFileSync('input.txt');
console.log("同步读取: " + data.toString());
console.log("程序执行完毕。");
[/code]
相关文章推荐
- Android Manifest 用法
- 什么是 GraphQL?
- Unix 即将迎来 50 岁
- 使用 HTTP 上传 G 级的文件之 Node.js 版本
- Spark RDD API详解(一) Map和Reduce
- mongo实现消息队列
- Node.js压缩web项目中的js,css和图片
- Linux VS Unix:Linux欲一统天下 Unix不死
- lwn拾遗:[sn3218 led drivers]-api解释-1
- async.js 学习记录
- 异步流程控制:7 行代码学会 co 模块
- Mootools 1.2教程 函数
- autoit InputBox 函数
- 文件遍历排序函数
- 一个小型js框架myJSFrame附API使用帮助
- Oracle 函数大全[字符串函数,数学函数,日期函数]第1/4页
- 详细分析交换机、路由器、集线器的区别和联系
- PowerShell打开或关闭光驱
- ASP下经常用的字符串等函数参考资料
- PostgreSQL教程(五):函数和操作符详解(1)