javascript - Running js file in terminal - Stack Overflow

I'm trying to run this simple file in an empty folder time.jsconst moment = require('momen

I'm trying to run this simple file in an empty folder

// time.js
const moment = require('moment')

function getDay() {
  var today = moment().day()
  console.log(today);
}

getDay()

using node time.js

But I get

Error: Cannot find module 'moment'

However I have run npm install -g moment and npm install moment.

What noob error am I doing?

I'm trying to run this simple file in an empty folder

// time.js
const moment = require('moment')

function getDay() {
  var today = moment().day()
  console.log(today);
}

getDay()

using node time.js

But I get

Error: Cannot find module 'moment'

However I have run npm install -g moment and npm install moment.

What noob error am I doing?

Share Improve this question asked Mar 5, 2017 at 23:40 softcodesoftcode 4,67812 gold badges44 silver badges69 bronze badges 4
  • If the folder is empty, then you forgot to add an package json and install moment inside this folder. So require can't find anything. Or is there a folder named node_modules present? – cyr_x Commented Mar 5, 2017 at 23:45
  • @cyrix so you can't just run a standalone .js file in the terminal ? – softcode Commented Mar 5, 2017 at 23:52
  • sure you can, but don't rely on npm packages if you didn't install them inside your project folder – cyr_x Commented Mar 5, 2017 at 23:53
  • i added an example on how to quickly set up npm for a project folder. (note: it's an minimal example) – cyr_x Commented Mar 5, 2017 at 23:57
Add a ment  | 

2 Answers 2

Reset to default 4

Just do the following mands on your console inside your folder:

npm init // just hit enter some times or follow the process
npm install moment --save
node time.js

Note: You could skip the npm init part but I wouldn't remend it due to dependency control.

you need to make sure you have initiated the package before requiring dependencies,

to install moment

npm install moment

to initialize the package

npm init

This will create the package.json, make sure that "moment^x.x.x" is available within the dependencies

Set your time.js as the main.js in package's scripts as well,

for example

"scripts": {
    "start": "node time.js",
  },

and then to run the app

npm start

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744027509a4545952.html

相关推荐

  • javascript - Running js file in terminal - Stack Overflow

    I'm trying to run this simple file in an empty folder time.jsconst moment = require('momen

    9天前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信