Node.js:如何将请求对象写入文件

时间:2019-01-17 08:00:21

标签: node.js fs writefile

要编写日志(请求信息),我尝试使用wirteFile和JSON.stringify方法。但是,它没有用。

请帮助我完成这项工作

var express = require('express');
var router = express.Router();
var fs = require('fs');

router.post('/', function(req, res, next) {
 fs.writeFile('requestLog.txt', JSON.stringify(req), 'utf8', 
function(error, req){
    if(error) { console.log('error occurred') };
    res.send('success post request');
  })
});

module.exports = router;

4 个答案:

答案 0 :(得分:1)

如果您想将所有请求写入日志文件 我建议使用morgan - npm

morgan提供了许多选项来选择记录的内容和格式。

这里是一个例子:

var express = require('express')
var fs = require('fs')
var morgan = require('morgan')
var path = require('path')

var app = express()

// create a write stream (in append mode)
var accessLogStream = fs.createWriteStream(path.join(__dirname, 'access.log'), { flags: 'a' })

// setup the logger
app.use(morgan('combined', { stream: accessLogStream }))

app.get('/', function (req, res) {
  res.send('hello, world!')
})

答案 1 :(得分:0)

我猜你必须写错字

fs.writeFile('requestLog.txt', JSON.stringify(req.body), 'utf8'

答案 2 :(得分:0)

为此,我将使用专用的日志记录库,那里有几个不错的库。使用winston-express库,您可以轻松记录各种格式的请求。

例如

var express = require('express');
var expressWinston = require('express-winston');
var winston = require('winston');
var app = express();

app.use(expressWinston.logger({
    transports: [
      new winston.transports.File({ filename: 'express.log' })
    ],
    format: winston.format.combine(
      winston.format.json()
    )
  }));

app.get('/test', function(req, res, next) {
    res.send('All good');
});

app.listen(3000, function(){
  console.log(`Express Listening on port ${this.address().port}`);
});

一个日志条目的示例如下:


{
    "level": "info",
    "message": "HTTP GET /test",
    "meta": {
        "res": {
            "statusCode": 200
        },
        "req": {
            "url": "/test",
            "headers": {
                "host": "localhost:3000",
                "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:64.0) Gecko/20100101 Firefox/64.0",
                "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
                "accept-language": "en-GB,en;q=0.7,en-US;q=0.3",
                "accept-encoding": "gzip, deflate",
                "connection": "keep-alive",
                "upgrade-insecure-requests": "1",
                "if-none-match": "W/\"2-nOO9QiTIwXgNtWtBJezz8kv3SLc\""
            },
            "method": "GET",
            "httpVersion": "1.1",
            "originalUrl": "/test",
            "query": {}
        },
        "responseTime": 2
    }
}

答案 3 :(得分:0)

请允许我分享一个函数示例,该函数可以帮助您创建新文件并在其中存储数据:

 // Open the file for writing
  fs.open('your/path/nameOfFile.json', 'wx', (err, fileDescriptor)=>{
        //'w' - Open file for writing. The file is created (if it does not exist) 
        //or truncated (if it exists).
        //'wx' - Like 'w' but fails if the path exists.
        //'w+' - Open file for reading and writing. The file is created (if it does not exist)
        //or truncated (if it exists).
        //'wx+' - Like 'w+' but fails if the path exists.
        //open the file we want to create
        //wx:open the file for writing
        //fileDescriptor: part of callback returned, is a unique identifier
    if(!err && fileDescriptor){
      // Convert data to string
      const stringData = JSON.stringify(data)

      // Write to file and close it
      fs.writeFile(fileDescriptor, stringData,err=>{
        if(!err){
          fs.close(fileDescriptor,err=>{
            if(!err){
              callback(false)
            } else {
              callback('Error closing new file')
            }
          })
        } else {
          callback('Error writing to new file')
        }
      })
    } else {
      callback('Could not create new file, it may already exist')
    }
  })

祝你好运!