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
2 Answers
Reset to default 4Just 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