5-写文件

  打开node.js官网  找到api文档 点击DOS

  文件操作用的是File System模块 即fs模块

  调用模块必须先加载一下即require(),var fs=require('fs')
  只有全局模块不用加载 例如:process模块

  判断需不需要加载的方法:
    1.打开文档 查看该对应模块 能看到用法会告诉你要不要require
    2.点击Globals 会列出全局模块

  注意:打开api文档时会看到头部有个的框框
         绿色  Stability 2 代表稳定的api      可以使用
         橘色  Stability 1 代表正再测试的api  不能使用
         红色  Stability 0 代表废弃的api      不能使用

demo

var fs=require('fs')
var msg='hello world'

fs.writeFile('./hello.txt',msg,'utf8',function (err) {
    if(err){
        console.log('写文件出错,错误为'+err)
    }else {
        console.log('写文件成功')
    }
})

参数说明

调用fs.writeFile(file,data,[options],callback)写入
不知道参数是什么时可以查看文档 []扩起来的参数可传可不传
file:文件路径
data:数据 string 或 Buffer类型(二进制字节数据)
[options]:可选项 例如:可以穿utf8编码
callback:回调 执行这个函数时代表写操作结束

//回调函数默认有参数 是err错误对象
//若写文件成功 则err==null
//只要不等于null 就代表写文件失败

猜你喜欢

转载自blog.csdn.net/MDZZ___/article/details/91375283