前端开发nodeJs_文件写入读取接口

前端聊天室怎么开发
前端开发怎么算精通
女生前端开发英文怎么说

目录结构:
javascript 代码

    |
        +- controllers/ <– Controller
    | |
        | +- jsonFile.js <– 文件读写
        |
        +- router <– 路由文件
    | |
        | +- router.js <– 路由配置
        |
        +-data<–文件存储目录
    |
        +- server.js <– 入口文件
    |
        +- package.json <– 项目描述文件
    |
        +-processes.json<–pm2配置文件
    |
        +-run.bat<–启动脚本
    |
        +-stop.bat<–停止脚本
    |
        +- node_modules/ <– npm安装的所有依赖包

jsonFile.js:
javascript 代码

/**
* Created by fangdandan on 2017/11/07.
* 本地文件存储
*/
var fs = require(‘fs’)
module.exports = {
    writeFile: function(req, res) {
        let param = req.body
        console.log(‘准备写入文件’)
        fs.writeFile(‘data/’ + param.id + ‘.txt’, param.content, function(err) {
            if (err) {
                res.json({
                    result: false,
                    errorMsg: ‘保存失败’,
                    errorDetail: err.toString(),
                })
            } else {
                res.json({
                    result: true,
                    errorMsg: ‘保存成功’,
                })
                console.log(‘数据写入成功!’)
            }
        })
    },
    readFile: function(req, res) {
        let param = req.body
        fs.readFile(‘data/’ + param.id + ‘.txt’, function(err, data) {
            if (err) {
                res.json({
                    result: false,
                    errorMsg: ‘数据读取失败’,
                    errorDetail: err.toString(),
                })
            } else {
                console.log(‘异步读取文件数据: ‘ + data.toString())
                res.json({
                    result: true,
                    errorMsg: ‘数据读取成功’,
                    data: data.toString(),
                })
            }
        })
    },
}

router.js:
javascript 代码

const express = require(‘express’)
const router = express.Router()
const jsonFile = require(‘../controllers/jsonFile’)
// jsonFile
router.post(‘/Write_File_Data’, jsonFile.writeFile)
router.post(‘/Read_File_Data’, jsonFile.readFile)
module.exports = router

server.js:
javascript 代码

var express = require(‘express’)
var bodyParser = require(‘body-parser’) //用于处理 JSON, Raw, Text 和 URL 编码的数据
var app = express()
var router = require(‘./router/router’)
//设置跨域访问
app.all(‘*’, function(req, res, next) {
    res.header(‘Access-Control-Allow-Origin’, ‘*’)
    res.header(‘Access-Control-Allow-Headers’, ‘X-Requested-With’)
    res.header(‘Access-Control-Allow-Methods’, ‘PUT,POST,GET,DELETE,OPTIONS’)
    res.header(‘X-Powered-By’, ‘ 3.2.1’)
    res.header(‘Content-Type’, ‘application/json;charset=utf-8’)
    next()
})
app.use(bodyParser.json()) //解析json数据
app.use(bodyParser.urlencoded({ extended: true })) //解析form表单提交上来的数据
app.use(‘/’, router)
var server = app.listen(8888, function() {
    var host = server.address().address
    var port = server.address().port
    console.log(‘http://%s:%s’, host, port)
})

package.json:
json 代码

{
    “name”: “Demo”,
    “version”: “1.0.0”,
    “description”: “”,
    “main”: “server.js”,
    “scripts”: {
        “pm2”: “pm2 start processes.json”
    },
    “author”: “fangdandan”,
    “license”: “ISC”,
    “dependencies”: {}
}

processes.json:
json 代码

{
    “apps”: [
        {
            “name”: “Demo”, //名称
            “script”: “./server.js”, //程序入库
            “cwd”: “./”, //根目录
            “watch”: [“controllers”, “router”], //需要监控的目录
            “error_file”: “./logs/app-err.log”, //错误输出日志
            “out_file”: “./logs/app-out.log”, //日志
            “log_date_format”: “YYYY-MM-DD HH:mm Z” //日期格式
        }
    ]
}

run.bat:
json 代码

npm run pm2

stop.bat:
json 代码

pm2 delete -s Demo

注意:
1、安装node
2、npm install pm2 -g
3、npm install express
4、npm install fs
5、windows服务器,直接双击run.bat启动项目

调用接口:
javascript 代码

function readFile() {
    var param = {}
    param.id = 13
    $.ajax({
        url: ‘https://www.rokub.com:8888/Read_File_Data’,
        type: ‘POST’,
        data: param,
        success: function(data) {
            if (data.result) {
                var content = JSON.parse(data.data)
                console.log(content)
            }
        },
    })
}
function writeFile() {
    var param = {}
    param.id = 13
    param.content = ”
    var obj = [
        {
            id: ‘1’,
            name: ‘模式一’,
            data: [
                {
                    type: ‘1’,
                    data: [
                        {
                            num: 0,
                            isChecked: true,
                            bet: 55,
                        },
                        {
                            num: 1,
                            isChecked: true,
                            bet: 55,
                        },
                        {
                            num: 2,
                            isChecked: true,
                            bet: 55,
                        },
                        {
                            num: 3,
                            isChecked: true,
                            bet: 55,
                        },
                        {
                            num: 4,
                            isChecked: true,
                            bet: 55,
                        },
                    ],
                },
                {
                    type: ‘2’,
                    data: [
                        {
                            num: 0,
                            isChecked: true,
                            bet: 55,
                        },
                        {
                            num: 1,
                            isChecked: true,
                            bet: 55,
                        },
                        {
                            num: 2,
                            isChecked: true,
                            bet: 55,
                        },
                        {
                            num: 3,
                            isChecked: true,
                            bet: 55,
                        },
                        {
                            num: 4,
                            isChecked: true,
                            bet: 55,
                        },
                    ],
                },
            ],
        },
    ]
    param.content = JSON.stringify(obj)
    $.ajax({
        url: ‘https://www.rokub.com:8888/Write_File_Data’,
        type: ‘POST’,
        data: param,
        success: function(data) {
            console.log(data.errorMsg)
        },
    })
}
//获取地址参数值
function getParameter(param) {
    var reg = new RegExp(‘(^|&)’ + param + ‘=([^&]*)(&|$)’)
    var r = window.location.search.substr(1).match(reg)
    if (r != null) return decodeURI(r[2]) //可对 encodeURI() 函数编码过的 URI 进行解码
    return ”
}
前端开发 怎么赚外快
前端开发中怎么添加断点
html前端开发 空格怎么打
» 本文来自:前端开发者 » 《前端开发nodeJs_文件写入读取接口》
» 本文链接地址:https://www.rokub.com/7957.html
» 您也可以订阅本站:https://www.rokub.com
赞(0)
64K

评论 抢沙发

评论前必须登录!