Running JS on localhost - server js - javascript

I try to run the following script:
In terminal I have written: node server, but I got an error message:
Error: Cannot find module 'express'
at Function.Module._resolveFilename (module.js:555:15)
at Function.Module._load (module.js:482:25)
at Module.require (module.js:604:17)
at require (internal/module.js:11:18)
at Object. (/home/jwisniowski/Desktop/PROJEKTY/UJ_API_PEP/shop-app/server.js:1:79)
at Module._compile (module.js:660:30)
at Object.Module._extensions..js (module.js:671:10)
at Module.load (module.js:573:32)
at tryModuleLoad (module.js:513:12)
at Function.Module._load (module.js:505:3)
sever.js
const express = require('express')
const app = express()
const port = process.env.PORT || 3000
const fs = require('fs')
const api_endpoint = process.env.API_ENDPOINT || "http://localhost:8081/application-orchestration/v1"
fs.writeFileSync(
__dirname + '/application-web/config/env.js',
'var api_endpoint = "' + api_endpoint + '";'
);
app.use(express.static('./'))
app.get('/', (request, response) => {
response.send('Hello from Express!')
})
app.listen(port, (err) => {
if (err) {
return console.log('something bad happened', err)
}
console.log(`server is listening on ${port}`)
})

make sure you have express in your package.json and do npm install.
or
npm install express -s

delete your node_modules folder, make sure that you have express in your package.json, and do npm install.

You might have to install express globally ,
npm install -g express --save
OR
Install express locally to your project
npm install express --save

Related

cannot find module in node express

cannot find module in node express
Actual code
const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
error code in cmd
C:\Users\user\Desktop\project>npm express -v
7.5.3
C:\Users\user\Desktop\project>npm utils -v
7.5.3
C:\Users\user\Desktop\project>node server
node:internal/modules/cjs/loader:928
throw err;
^
Error: Cannot find module './utils'
Require stack:
- C:\Users\user\Desktop\project\node_modules\qs\lib\stringify.js
- C:\Users\user\Desktop\project\node_modules\qs\lib\index.js
- C:\Users\user\Desktop\project\node_modules\express\lib\middleware\query.js
- C:\Users\user\Desktop\project\node_modules\express\lib\application.js
- C:\Users\user\Desktop\project\node_modules\express\lib\express.js
- C:\Users\user\Desktop\project\node_modules\express\index.js
- C:\Users\user\Desktop\project\server.js
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:925:15)
at Function.Module._load (node:internal/modules/cjs/loader:769:27)
at Module.require (node:internal/modules/cjs/loader:997:19)
at require (node:internal/modules/cjs/helpers:92:18)
at Object.<anonymous> (C:\Users\user\Desktop\project\node_modules\qs\lib\stringify.js:3:13)
at Module._compile (node:internal/modules/cjs/loader:1108:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1137:10)
at Module.load (node:internal/modules/cjs/loader:973:32)
at Function.Module._load (node:internal/modules/cjs/loader:813:14)
at Module.require (node:internal/modules/cjs/loader:997:19) {
code: 'MODULE_NOT_FOUND',
requireStack: [
'C:\\Users\\user\\Desktop\\project\\node_modules\\qs\\lib\\stringify.js',
'C:\\Users\\user\\Desktop\\project\\node_modules\\qs\\lib\\index.js',
'C:\\Users\\user\\Desktop\\project\\node_modules\\express\\lib\\middleware\\query.js',
'C:\\Users\\user\\Desktop\\project\\node_modules\\express\\lib\\application.js',
'C:\\Users\\user\\Desktop\\project\\node_modules\\express\\lib\\express.js',
'C:\\Users\\user\\Desktop\\project\\node_modules\\express\\index.js',
'C:\\Users\\user\\Desktop\\project\\server.js'
]
}
first try to remove the globally installed express
then initialize a package.json file with npm init. Here you will have a list of your dependencies, scripts and name of your package and some other data.
Then install express with npm i express.
after installing try to run it with node server.js or npm start if you have written the script to run the start command in package.json
I got the answer
Download utils https://www.npmjs.com/package/utils
this is the error
C:\Users\user\Desktop\project>
node server
node:internal/modules/cjs/loader:928
throw err;
^
Error: Cannot find module 'utils'
Require stack:
- C:\Users\user\Desktop\project\server.js
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:925:15)
at Function.Module._load (node:internal/modules/cjs/loader:769:27)
at Module.require (node:internal/modules/cjs/loader:997:19)
at require (node:internal/modules/cjs/helpers:92:18)
at Object.<anonymous> (C:\Users\user\Desktop\project\server.js:3:15)
at Module._compile (node:internal/modules/cjs/loader:1108:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1137:10)
at Module.load (node:internal/modules/cjs/loader:973:32)
at Function.Module._load (node:internal/modules/cjs/loader:813:14)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:12) {
code: 'MODULE_NOT_FOUND',
requireStack: [ 'C:\\Users\\user\\Desktop\\project\\server.js' ]
}
C:\Users\user\Desktop\project>
npm i utils
added 43 packages, removed 2 packages, changed 3 packages, and audited 110 packages in 16s
found 0 vulnerabilities
C:\Users\user\Desktop\project>node server
Example app listening at http://localhost:3000
^C
C:\Users\user\Desktop\project>

Unable to run docker image, Docker looking for different extension

I have the below Dockerfile:
# Use NodeJS base image
FROM node:12
# Create app directory
#RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
# Install app dependencies
# A wildcard is used to ensure both package.json AND package-lock.json are copied
# where available (npm#5+)
COPY package*.json /usr/src/app/
COPY src/. /usr/src/app # this is to copy contents of src/ one level up otherwise they aren't recognised
RUN npm install
# Bundle app source
COPY . /usr/src/app/
#RUN rm -f /usr/src/app/src/*
EXPOSE 8080
# Define the Docker image's behavior at runtime
CMD ["node", "server.js"]
But on running the docker image after a successful build, below error appears:
internal/modules/cjs/loader.js:965
throw err;
^
Error: Cannot find module '/usr/src/app/server.js'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:962:15)
at Function.Module._load (internal/modules/cjs/loader.js:838:27)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
at internal/main/run_main_module.js:17:47 {
code: 'MODULE_NOT_FOUND',
requireStack: []
}
Since I have a server.ts file and docker is somehow looking for server.js. On changing the extension, its unable to import other typescript files. Below is my server.ts:
import cors from 'cors';
import express from 'express';
import {sequelize} from './sequelize';
import {IndexRouter} from './controllers/v0/index.router';
import bodyParser from 'body-parser';
import {config} from './config/config';
import {V0_FEED_MODELS} from './controllers/v0/model.index';
(async () => {
await sequelize.addModels(V0_FEED_MODELS);
//await sequelize.addModels(V0_USER_MODELS);
await sequelize.sync();
const app = express();
const port = process.env.PORT || 8080;
app.use(bodyParser.json());
app.use(cors({
allowedHeaders: [
'Origin', 'X-Requested-With',
'Content-Type', 'Accept',
'X-Access-Token', 'Authorization',
],
methods: 'GET,HEAD,OPTIONS,PUT,PATCH,POST,DELETE',
origin: config.url,
}));
app.use('/api/v0/', IndexRouter);
// Root URI call
app.get( '/', async ( req, res ) => {
res.send( '/api/v0/' );
} );
// Start the Server
app.listen( port, () => {
console.log( `server running ${config.url}` );
console.log( `press CTRL+C to stop server` );
} );
})();
Why is docker picking up server.js automatically? where can I configure the docker to do otherwise?
FROM node:12
WORKDIR /usr/src/app
COPY . .
RUN npm install
EXPOSE 8080
CMD ["node", "server.js"]
I think this is what you are trying to do. It should work fine. If you're trying to do anything else please let me know.

Running an angular app using node js

I have a html page and a serviceController.js, I need to automatically run the app through node js. Sorry for the naive question but am unable to run it. My serviceController.js looks like this :
var app = angular.module("app", []);
app.controller('serviceController', ['$scope', '$interval','$http', function($scope, $interval, $http)
{ $scope.service1 = {//and so on..
}
I was following an example and I have tried the following: created a package.json :
{ "name": "express-html",
"version": "0.0.1",
"dependencies": {
"express": "^4.11.0"
}}
My server.js looks like this :
var express = require("express");
var app = express();
var path = require("path");
app.get('/',function(req,res){
res.sendFile(path.join(__dirname+'/index.html'));
});
app.listen(3000);
console.log("Running at Port 3000");
But, when I try starting the application from terminal using: node server.js. I get the following error :
(function (exports, require, module, __filename, __dirname)
{ var app = angular.module("app", []);
^ReferenceError: angular is not defined at Object.<anonymous> (/Users/dem/Desktop/frontend/task3/serviceController.js:1:81)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (/Users/dem/Desktop/frontend/task3/server.js:5:19)
at Module._compile (module.js:570:32)
Please guide!
app.use("/", express.static(__dirname)); Use this in place of
res.sendFile(path.join(__dirname+'/index.html'));
Update server file to serve a static directory
like app.use(express.static('dirPath'))
For more detail visit Serving static files in Express

Error on build JavaScript project Travis-CI

I have a project which I am building locally with Gulp.js. But when I push it to GitHub and Travis start building it. I get the following error:
module.js:338
throw err;
^
Error: Cannot find module 'gulp-concat'
at Function.Module._resolveFilename (module.js:336:15)
at Function.Module._load (module.js:278:25)
at Module.require (module.js:365:17)
at require (module.js:384:17)
at Object.<anonymous> (/home/travis/build/thyagostall/freecell/gulpfile.js:4:11)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Module.require (module.js:365:17)
The .travis.yml:
language: node_js
node_js:
- "0.12"
before_script:
- npm install -g gulp gulp-concat gulp-connect gulp-html-replace gulp-eslint
script: gulp
Also my gulpfile.js:
var gulp = require('gulp'),
connect = require('gulp-connect'),
concat = require('gulp-concat'),
htmlreplace = require('gulp-html-replace');
var distDir = './build/',
sourceDir = './src/';
gulp.task('webserver', function() {
connect.server({
root: distDir,
port: 2345,
livereload: true
});
gulp.watch('src/**/*.*', ['build', 'images', 'styles', 'vendor']);
});
gulp.task('images', function() {
gulp.src(sourceDir + '**/*.{jpg,png,gif}')
.pipe(gulp.dest(distDir));
});
gulp.task('styles', function() {
gulp.src(sourceDir + '**/*.css')
.pipe(gulp.dest(distDir));
});
gulp.task('build', function() {
gulp.src([sourceDir + '**/utility.js', sourceDir + '**/game_events.js', sourceDir + '**/memento.js', sourceDir + '**/*.js'])
.pipe(concat('main.js'))
.pipe(gulp.dest(distDir))
.pipe(connect.reload());
});
gulp.task('vendor', function() {
gulp.src(sourceDir + '**/*.html')
.pipe(htmlreplace({
'vendor': 'vendor.js',
'js': 'main.js'
}))
.pipe(gulp.dest(distDir));
});
gulp.task('lint', function() {
gulp.src(sourceDir + '**/*.js')
.pipe(eslint())
.pipe(eslint.format())
});
gulp.task('default', ['build', 'images', 'styles', 'vendor']);
Is there any obvious thing I am missing?
First, change your .travis.yml to this:
language: node_js
node_js:
- "0.12"
before_script:
- npm install -g gulp
script: gulp
You only need to install gulp globally because this provides the gulp commmand line tool. Per the official npm documentation:
There are two ways to install npm packages: locally or globally. You choose which kind of installation to use based on how you want to use the package.
If you want to use it as a command line tool, something like the grunt CLI, then you want to install it globally. On the other hand, if you want to depend on the package from your own module using something like Node's require, then you want to install locally.
Second, I did some sleuthing on your github account (linked from your StackOverflow profile) and found the project you're trying to build. Looking at the package.json I see that there is no gulp-concat among the devDependencies. This is probably due to typing:
npm install gulp-concat
instead of:
npm install gulp-concat --save-dev
Which would explain why you can build the project locally, but it fails on Travis-CI. Adding the gulp-concat to yourdevDependencies should resolve the issue.

MissingSchemaError: Schema hasn't been registered for model "Post"

I have been following the tutorial on MEAN stack (https://thinkster.io/mean-stack-tutorial/) and have stumbled on a problem. When trying to do npm start, I am getting an error message, specifically the following:
C:\Linked\linked>npm start
> linked#0.0.0 start C:\Linked\linked
> node ./bin/www
C:\Linked\linked\node_modules\mongoose\lib\index.js:329
throw new mongoose.Error.MissingSchemaError(name);
^
MissingSchemaError: Schema hasn't been registered for model "Post".
Use mongoose.model(name, schema)
at Mongoose.model (C:\Linked\linked\node_modules\mongoose\lib\index.js:329:13)
at Object.<anonymous> (C:\Linked\linked\routes\index.js:2:21)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Module.require (module.js:365:17)
at require (module.js:384:17)
at Object.<anonymous> (C:\Linked\linked\app.js:8:14)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Module.require (module.js:365:17)
at require (module.js:384:17)
at Object.<anonymous> (C:\Linked\linked\bin\www:7:11)
npm ERR! Windows_NT 6.3.9600
npm ERR! argv "C:\\Program Files\\nodejs\\\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "start"
npm ERR! node v0.12.3
npm ERR! npm v2.9.1
npm ERR! code ELIFECYCLE
npm ERR! linked#0.0.0 start: `node ./bin/www`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the linked#0.0.0 start script 'node ./bin/www'.
npm ERR! This is most likely a problem with the linked package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! node ./bin/www
npm ERR! You can get their info via:
npm ERR! npm owner ls linked
npm ERR! There is likely additional logging output above.
npm ERR! Please include the following file with any support request:
npm ERR! C:\Linked\linked\npm-debug.log
The following are the files that likely contain the problem. I tried tinkering around different lines, mainly in routes\index.ejs, but I have not been able to fix this problem yet.
routes\index.ejs
var mongoose = require('mongoose');
var Post = mongoose.model('Post');
var Comment = mongoose.model('Comment');
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;
// GET posts
router.get('/posts', function(req, res, next) {
Post.find(function(err, posts){
if(err){ return next(err); }
res.json(posts);
});
});
// POST a post
router.post('/posts', function(req, res, next) {
var post = new Post(req.body);
post.save(function(err, post){
if(err){ return next(err); }
res.json(post);
});
});
...
models\Posts.js
var mongoose = require('mongoose');
var PostSchema = new mongoose.Schema({
title: String,
link: String,
upvotes: {type: Number, default: 0},
comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Comment' }]
});
mongoose.model('Post', PostSchema);
// Upvote method
PostSchema.methods.upvote = function(cb) {
this.upvotes += 1;
this.save(cb);
};
public\javascripts\angularApp.js
var mongoose = require('mongoose');
require('./models/Posts');
require('./models/Comments');
mongoose.connect('mongodb://localhost/news');
var app = angular.module('linked', ['ui.router']);
Please let me know if I anything is unclear.
The issue is that you are not including the models files in your index.ejs files - you are just referencing model references within mongoose.
Where you have
var Post = mongoose.model('Post');
var Comment = mongoose.model('Comment');
Replace these with require statements that link to your models/Posts.js file
var Post = require('models/Posts');

Categories