Node.js 文件系统

来源:互联网 发布:苏州智科讯优网络 编辑:程序博客网 时间:2024/05/21 09:43




无标题

Node.js 提供一组类似 UNIX(POSIX)标准的文件操作API。 Node 导入文件系统模块(fs)语法如下所示:

  1. var fs = require("fs")


异步和同步

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 文件, 代码如下:

  1. var fs = require("fs");// 异步读取
  2. fs.readFile('input.txt', function (err, data) {if (err) {return console.error(err);}
  3. console.log("异步读取: " + data.toString());});// 同步读取var data = fs.readFileSync('input.txt');
  4. console.log("同步读取: " + data.toString());
  5. console.log("程序执行完毕。");

0 0
原创粉丝点击