前言:
fs读取本地的txt文件。
实现效果:
实现步骤:
安装fs模块
npm i fs --save
utf-8 的txt文件读取
1、router.local.js
module.exports = app => {
const { router, controller, middleware } = app;
router.get("/getTxtXiaoshuo", controller.testApi.fsxiaoshuo.getTxtXiaoshuo);
}
2、controller/testApi/fsxiaoshuo.js
fs.readFile(地址,格式,回调函数)
fs.readFileSync('hello.txt',{flag:'r',encoding:'utf-8'}) //utf-8 格式
const Controller = require('egg').Controller;
class FsXiaoShuoController extends Controller {
async getTxtXiaoshuo(ctx) {
const requestPromise = new Promise((resolve, reject) => {
//fs.readFile(地址,格式,回调函数)
fs.readFile('D:\\1.txt',function (err,data) {
console.log('拿到数据了:')
if(err){
return resolve({
code:400,
data:err
})
}else{
return resolve({
code:200,
data:data
})
}
})
})
})
const result = await requestPromise;
ctx.body = result
}
}
module.exports = FsXiaoShuoController;
gb2312 格式的txt文件读取
1、router.local.js
module.exports = app => {
const { router, controller, middleware } = app;
router.get("/getTxtXiaoshuo", controller.testApi.fsxiaoshuo.getTxtXiaoshuo);
}
2、安装插件(gb2312 必须有的)
npm install iconv-lite
3、controller/testApi/fsxiaoshuo.js
fs.readFile(地址,格式,回调函数)
const Controller = require('egg').Controller;
class FsXiaoShuoController extends Controller {
async getTxtXiaoshuo(ctx) {
const requestPromise = new Promise((resolve, reject) => {
//fs.readFile(地址,格式,回调函数)
fs.readFile('D:\\1.txt',function (err,data) {
console.log('拿到数据了:')
if(err){
return resolve({
code:400,
data:err
})
}else{
let content = iconv.decode(data, 'GB2312').toString();
return resolve({
code:200,
content
})
}
})
})
})
const result = await requestPromise;
ctx.body = result
}
}
module.exports = FsXiaoShuoController;