softcode
softcode

Reputation: 4648

Running js file in terminal

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?

Upvotes: 3

Views: 14393

Answers (2)

cyr_x
cyr_x

Reputation: 14257

Just do the following commands 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 recommend it due to dependency control.

Upvotes: 4

xxfast
xxfast

Reputation: 737

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

Upvotes: 0

Related Questions