Concerning the Back End BoilerPlate

The default script server.js doesn’t import any other script file with ‘require()’ function, It just sends the html file to the root path and listens the port defined by env variable PORT.

Since this script shouldn’t be edited. How can I add a path in order to import my app script file when I run Node server? For example:

const myApp= require('./myapp')

Hey @sharkantropo,

Which challenge are you reffering to?

The boilerplate for TimeStamp API challenge.

Elaborating further. I’ve downloaded it and started coding my app script, however, I don’t know how to run it without editing server.js (although the edition is quite minor, I only want to add an import for my script). Since the instructions on comments at the beginning clearly states not editing the file:

 /******************************************************
 * PLEASE DO NOT EDIT THIS FILE
 * the verification process may break
 * ***************************************************/

'use strict';

var fs = require('fs');
var express = require('express');
var app = express();

if (!process.env.DISABLE_XORIGIN) {
  app.use(function(req, res, next) {
    var allowedOrigins = ['https://narrow-plane.gomix.me', 'https://www.freecodecamp.com'];
    var origin = req.headers.origin || '*';
    if(!process.env.XORIG_RESTRICT || allowedOrigins.indexOf(origin) > -1){
         console.log(origin);
         res.setHeader('Access-Control-Allow-Origin', origin);
         res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    }
    next();
  });
}

app.use('/public', express.static(process.cwd() + '/public'));

app.route('/_api/package.json')
  .get(function(req, res, next) {
    console.log('requested');
    fs.readFile(__dirname + '/package.json', function(err, data) {
      if(err) return next(err);
      res.type('txt').send(data.toString());
    });
  });
  
app.route('/')
    .get(function(req, res) {
		  res.sendFile(process.cwd() + '/views/index.html');
    })

// Respond not found to all the wrong routes
app.use(function(req, res, next){
  res.status(404);
  res.type('txt').send('Not found');
});

// Error Middleware
app.use(function(err, req, res, next) {
  if(err) {
    res.status(err.status || 500)
      .type('txt')
      .send(err.message || 'SERVER ERROR');
  }  
})

app.listen(process.env.PORT, function () {
  console.log('Node.js listening ..');
});

Hey, I ended up editing the server.js file to import my timestamp micro service route handlers and passed. It didn’t break the verification process in any way.

2 Likes

Great job… In your case, if you actually know what you’re modifying, you might be able to get away with it. That warning is there to prevent newcomers that doesn’t really have an idea of what to do. But still be careful, because it can break.

1 Like