Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
524 views
in Technique[技术] by (71.8m points)

javascript - SyntaxError: function statements require a function name

This is my code where I am using Node express and EJS to make a To-do list website. Here I am exporting the date.js file in my app.js to get the current date.

This is my app.js:

const express = require("express");
const bodyParser = require("body-parser");
const date = require(__dirname + "/date.js");

const app = express();

let items= ["Buy Food","Cook Food","Eat Food"];
let workItems=[];

app.use(bodyParser.urlencoded({extended:true}));
app.use(express.static("public"));

app.set('view engine', 'ejs');

app.get("/", function(req, res) {
  let day=date();
  res.render("list", {
    ListTitle: day,
    newListItems:items
  });
});

app.get("/work",function(req,res){
  res.render("list", {
    ListTitle: "Work List",
    newListItems:workItems
  });
});

app.post("/work",function(req,res){
  let item=req.body.newItem;
  workItems.push(item);
  res.redirect("/");
});

app.post("/",function(req,res){
  let item=req.body.newItem;
  if(req.body.list==="Work"){
    workItems.push(item);
    res.redirect("/work");
  }else{
    item.push(item);
    res.redirect("/");
  }
});

app.listen(3000, function() {
  console.log("server is up and running at port 3000");
});

when I try to run this in my hyper terminal, it throws an error: SyntaxError: function statements require a function name

It's working fine if I don't export date.js file, and instead write the content of function getDate(), of date.js file in app.js. which means this line is generating the error

const date = require(__dirname + "/date.js");

According to me either the error is in this line or the date.js file. But I am not able to find out the problem.

here is my date.js file:

module.exports= getDate;

function getDate()
{
  let today = new Date();

  let options = {
    weekday:"long",
    day:"numeric",
    month:"long"
  };
  let day = today.toLocaleDateString("en-US", options);
  return day;
}

Can somebody help me resolve this problem?

P.S. This to-do list web app is a part of angela Yu web development course. I am following the same instructions as given in the course and still getting this error.

Here is the error message:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Instead of accessing the getDate module with __dirname, try giving the full relative path. I'm not sure what your project structure looks like, but if app.js and date.js are in the same directory, write const date = require("./date.js").


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...