DEV Community

khaled-17
khaled-17

Posted on

How do I print my console.log output to a text file using Node.js and Express

Recently,

I was working on a project using MERN Stack
And when I got to the stage
Uploading the code of node.js to the cloud. I had a problem. I don't know what it really is, but I had to see the output of the console log to know where the problem is.
The problem here also is that I will not be able to see the console log output because there is a problem with the hosting service provider.
I had to find a quick solution for you so that the hosting customer service would respond to us

step 1

in index.js look like that

const express = require('express');
const fs = require('fs');
const path = require('path');
const util = require('util');
const app = express();

 const logFilePath = path.join(__dirname, 'console-log.txt');

 const logStream = fs.createWriteStream(logFilePath, { flags: 'a' });

 console.log = (...args) => {
  const logMessage = util.format(...args);
  //  const logMessage = `[${new Date().toISOString()}] ${req.method} ${req.url}// ${ util.format(...args)}\n`;

  logStream.write(`${new Date().toISOString()} '>>>>>>>>     ' ${logMessage} '\n'`);
  //   logStream.write(`[] ${req.method} ${req.url}// ${ logMessage}\n`);
  process.stdout.write(logMessage + '\n'); // to save default behavior
};

// and  console.error   
console.error = (...args) => {

  const logMessage = util.format(...args);
  logStream.write(logMessage + '\n');
  process.stderr.write(logMessage + '\n'); // to save default behavior
};

// test case  console.log  and  console.error  
console.log('hello from console.log +++++');
console.error("hello from console.error +++++++++");



app.get('/', (req, res) => {
  res.send(`hello`);
  console.log('index work');

});



app.get('/error', (req, res) => {
  const filePath = path.join(__dirname, 'console-log.txt');
  const buttonHTML = '<form action="/clear-log" method="post"><button>delete </button></form>';
  const reloadButtonHTML = '<form onclick="refreshPage() method="get"><button>refreshPage</button></form>';

  // reading file contnt
  fs.readFile(filePath, 'utf8', (err, content) => {
    if (err) {
      console.error('error in reading:', err);
      res.status(500).send('error in reading ');
      return;
    }

    const logContent = `<pre>${content}</pre>`;
    const fullHTML = buttonHTML +reloadButtonHTML+ logContent;
    res.send(fullHTML);
  });
});

// add new rout to handel DELETE  
app.post('/clear-log', (req, res) => {
  const filePath = path.join(__dirname, 'console-log.txt');

  // DELETE file content 
  fs.writeFile(filePath, '', err => {
    if (err) {
      console.error('error in DELETE file content :', err);
      res.status(500).send('error   DELETE file content ');
      return;
    }

    // read file content 
    fs.readFile(filePath, 'utf8', (readErr, content) => {
      if (readErr) {
        console.error('error in reading', readErr);
        res.status(500).send('error in reading');
        return;
      }

      const logContent = `<pre>${content}</pre>`;
      const fullHTML = '<p>  DELETE file content  is done:</p>' + logContent;
      // res.send(fullHTML);
      res.redirect('/error');

    });
  });
});





app.get('/notfound', (req, res) => {
  console.log('notfound');
  res.send('notfound');
});
console.log('index work');


const userRouter = require('./userRouter'); // Import the user router module

// Existing code for logging and other routes

// Use the userRouter for user registration route
app.use('/user', userRouter); // You can change 'user' to your desired route prefix



//in port  3000
app.listen(3000, () => {
  console.log('run in port 3000');
});

Enter fullscreen mode Exit fullscreen mode

step 2 userRouter.js

const express = require('express');
const router = express.Router();
const userController = require('./userController'); // Import the user controller module



console.log('rowt work');
// Define a route for user registration
router.get('/register', userController.registerUser);

module.exports = router;

Enter fullscreen mode Exit fullscreen mode

step 3 userController.js

// userController.js
const registerUser = (req, res) => {
    // Your registration logic here
    // Example: Save user data to a database
    console.log('*****// hello from  userController.js    ******');
    // res.status(200).send('User registered successfully');
  };

  module.exports = {
    registerUser
  };

Enter fullscreen mode Exit fullscreen mode

Image description

and finaly vist it

http://localhost:3000/error

we see that

Image description

Top comments (0)