一、使用node运行js代码
在js代码当前文件夹打开终端,输入 node 文件名.js
就可以运行js代码,和终端java运行代码差不多。
二、fs文件系统模块
fs 文件系统模块是node操作文件的模块,使用时要先导入fs模块,const fs = require('fs')
。
1、readFile
readFile用来读取指定文件内容,它有三个参数readFile(path,code,callback)
,path是文件的路径,code是读取的编码方式(可写可不写),callback指回调函数。回调函数里面有两个形参err和dataStr,err是读取失败返回的错误信息,dataStr是读取成功的结果。
const fs = require('fs')
fs.readFile('file/hello.txt','utf-8',function (err, dataStr) {
if(err){
console.log('读取失败'+err);
}else{
console.log('读取成功\n'+dataStr)
}
})
2、writeFile
writeFile用来读取指定文件内容,它有三个参数readFile(path,data,code,callback)
,path是文件的路径,data 是写入的内容,code是读取的编码方式(可写可不写),callback指回调函数。回调函数里面有形参err,err是写入失败返回的错误信息。
const fs = require('fs')
fs.writeFile('file/hello.txt', &#