Home > Blockchain >  can i console log a file or data wihtout starting node server?
can i console log a file or data wihtout starting node server?

Time:06-28

const express = require('express');
const fs = require('fs');
const app = express();
app.set('view engine', 'ejs');
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({
  extended: true
}));

fs.readFile('test.html', 'utf8', (err, data) => {
    if (err) {
      console.error(err);
      return;
    }
    console.log(data);
  })
  app.listen(3005,()=>{
    console.log("Server is Up on PORT 3005");
})

I want to console.log(data) without running nodejs server ? but how ?

thanks in advance

CodePudding user response:

If you would like to perform operations in JS without starting up a server, this is traditionally known as a script. Scripts are usually run in an on-demand fashion rather than constantly running like a server. If you create a new script named read-file.js, you could run the script by running node read-file.js in your terminal.

To read a static file without a server, you could use the following script:

const { readFile } = require('fs');
const { join } = require('path');

readFile(join(__dirname, 'test.html'), 'utf8', (err, data) => {
    if (err) {
        console.log(err);
    }
    
    console.log(data);
});

CodePudding user response:

You could pass through an environment variable when running your node process. For example:

RUN=false npm run dev

Then within your code, process.env.RUN will be set based on what you passed in the command.

Simply surround the logic that starts the server based on the status of RUN:

if (process.env.RUN === "true") {
    // Start your server 
} else {
    // Do something
    fs.readFile('test.html', 'utf8', (err, data) => {
        if (err) {
          console.error(err);
          return;
        }
        console.log(data);
      })
      app.listen(3005,()=>{
        console.log("Server is Up on PORT 3005");
    })
}
  • Related