I am learning nodejs from Courseera and wanted to run a code from command prompt in windows 10.But this error Cannot find module always occurs.Iam completely at aloss what this means.
I have tried all the methods given in the other stack overflow threads but couldn't solve the issue.
node and npm are correctly installed with versions v6.9.2 and 3.10.9 respectively.
D:\shaury\node-http\public>node -v
v6.9.2
D:\shaury\node-http\public>npm -v
3.10.9
This is the problem which is occcuring:
D:\shaury\node-http\public>node serve
module.js:471
throw err;
^
Error: Cannot find module 'D:\shaury\node-http\public\serve'
at Function.Module._resolveFilename (module.js:469:15)
at Function.Module._load (module.js:417:25)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:394:7)
at startup (bootstrap_node.js:149:9)
at bootstrap_node.js:509:3
There's a typo in your code.
var http = require('http');
var hostname = 'localhost';
var port = 3000;
var server = http.createServer(function(req, res){
console.log(req.headers);
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('<html><body><h1>Hello World</h1></body></html>');
});
//here you should surround your string in 'quotation marks' but make sure to use `backticks`
server.listen(port, hostname, function(){
console.log(`Server running at http://${hostname}:${port}/`);
});
Edit: actually you might need to check that you are in the correct directory. When you launch your app it should be from the directory that your .js file is or else supply the path.
Related
So I just installed dotenv in my project and I am requiring it with this code:
require("dotenv").config();
And then using my variables like so:
app.listen(process.env.PORT, () => {
console.log(`Listening on ${process.env.ENDPOINT}:${process.env.PORT}`);
});
In .env:
ENDPOINT = "127.0.0.1";
PORT = 5000;
Code works just fine if I add the variables as constants within my js file, but when I try to access the variables through process.env I get:
events.js:291
throw er; // Unhandled 'error' event
^
Error: listen EACCES: permission denied 5000;
at Server.setupListenHandle [as _listen2] (net.js:1299:21)
at listenInCluster (net.js:1364:12)
at Server.listen (net.js:1461:5)
at Function.listen (C:\Users\Darkbound\Desktop\TouchScreenProject\SmartFactory\server\node_modules\express\lib\application.js:618:24)
at Object. (C:\Users\Darkbound\Desktop\TouchScreenProject\SmartFactory\server\main.js:34:5)
at Module._compile (internal/modules/cjs/loader.js:1251:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1272:10)
at Module.load (internal/modules/cjs/loader.js:1100:32)
at Function.Module._load (internal/modules/cjs/loader.js:962:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
at internal/main/run_main_module.js:17:47 Emitted 'error' event on Server instance at:
at emitErrorNT (net.js:1343:8)
at processTicksAndRejections (internal/process/task_queues.js:80:21) { code: 'EACCES',
errno: -4092, syscall: 'listen', address: '5000;', port: -1 }
I have tried using other ports, I get the same error on all ports, I have tried 3000, 3010, 5000 etc.
If the other variable, ENDPOINT is accesses without problems, so if I do:
const PORT = 5000;
app.listen(PORT, () => {
console.log(`Listening on ${process.env.ENDPOINT}:${PORT}`);
});
This works.
EDIT SOLVED: I found the issue, as usual, right after I ask the question. The issue is that I have ; at the end of each variable in the .env file. this happened because I copy/pasted the variable from my javascript and I only deleted the const but forgot about ;
I found the issue, as usual, right after I ask the question. The issue is that I have ; at the end of each variable in the .env file. this happened because I copy/pasted the variable from my javascript and I only deleted the const but forgot about ;
I am learning Node.js via the book Node.js the Right Way. I am trying to run the following example to watch changes to a file called target.txt that resides in the the same directory as the .js file.
"use strict";
const
fs = require('fs'),
spawn = require('child_process').spawn,
filename = process.argv[2];
if (!filename) {
throw Error("A file to watch must be specified!");
}
fs.watch(filename, function () {
let ls = spawn('ls', ['-lh', filename]);
ls.stdout.pipe(process.stdout);
});
console.log("Now watching " + filename + " for changes...");
I get the following error when I change the text file and save it:
events.js:160
throw er; // Unhandled 'error' event
^
Error: spawn ls ENOENT
at exports._errnoException (util.js:1018:11)
at Process.ChildProcess._handle.onexit (internal/child_process.js:193:32)
at onErrorNT (internal/child_process.js:367:16)
at _combinedTickCallback (internal/process/next_tick.js:80:11)
at process._tickCallback (internal/process/next_tick.js:104:9)
Node.js version: v6.11.0
IDE: Visual Studio Code 1.13.1
OS: Windows 10 64x
There's no ls on Windows, you should use dir instead.
However, that's not an executable. To run .bat and .cmd files you can:
Spawn cmd.exe and pass those files as arguments:
require('child_process').spawn('cmd', ['/c', 'dir']);
Use spawn with the shell option set to true:
require('child_process').spawn('dir', [], { shell: true });
Use exec instead of spawn:
require('child_process').exec('dir', (err, stdout, stderr) => { ... });
For more on that, take a look at this section in the official docs.
EDIT:
I'm not sure I understood you question in the comment correctly, but if you go for the second option, for example, you code will look like this:
...
fs.watch(filename, function () {
let dir = spawn('dir', [filename], { shell: true });
dir.stdout.pipe(process.stdout);
});
...
Please, keep in mind you may need to adjust this code slightly. I'm writing all this from memory as I don't have access to a Windows machine right now, so I can't test it myself.
I'm trying to start a very simple server on my Mac so I can access a file from localhost.
I have node and express installed and this is all that it is in my server file.
var express = require('express'),
app = express();
app.use(express.static(__dirname, '/'));
app.listen(8080);
console.log("App listening on port 8080");
When I try to do:
node server
I get this as a response:
/Users/mt_slasher/node_modules/express/node_modules/serve-static/index.js:47
var opts = Object.create(options || null)
^
TypeError: Object prototype may only be an Object or null: /
at Function.create (native)
at Function.serveStatic (/Users/mt_slasher/node_modules/express/node_modules/serve-static/index.js:47:21)
at Object.<anonymous> (/Users/mt_slasher/Desktop/My Projects/Basket/Site/server.js:4:23)
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 Function.Module.runMain (module.js:501:10)
at startup (node.js:129:16)
at node.js:814:3
I've run this same file on a Windows machine with the same files and had no problem.
After some digging, I found this line seems to be the main culprit:
app.use(express.static(__dirname, '/'));
Can someone tell me what might be happening?
That is because you are passing "/" as second parameter (options)
app.use(express.static(__dirname + '/'));
See serve-static:
function serveStatic(root, options) ...
https://github.com/expressjs/serve-static/blob/master/index.js
Also note that it would be better to use a different directory than your root e.g. express.static(__dirname + '/public') to avoid exposing your root.
express.static is used to define directory where your "static" files reside look at here for more info.
It accepts only a string with the path you want to be static:
So your code should be:
app.use(express.static('/'));
Or
app.use(express.static(__dirname + '/'));
But that doesn't make much sense, imho.
Remove the line or define the real path where your assets files are.
The second parameter you are passing to express.static is incorrect. remove the second parameter.
app.use(express.static(__dirname));
I'm starting out with node.js and sequelize and I get the following error:
/home/cbaket/test/test.js:9
.complete(function(err) {
^
TypeError: undefined is not a function
at Object.<anonymous> (/home/cbaket/test/test.js:9:6)
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 Function.Module.runMain (module.js:501:10)
at startup (node.js:129:16)
at node.js:814:3
My file: test.js is:
var Sequelize = require('sequelize');
var sequelize = new Sequelize('apidb', 'apidb', 'apidb', {
dialect: "mysql", // or 'sqlite', mysql', 'mariadb'
port: 3306 // or 5432 (for postgres)
});
sequelize
.authenticate()
.complete(function(err) {
if (!!err) {
console.log('Unable to connect to the database:', err)
} else {
console.log('Connection has been established successfully.')
}
});
I'm following one of the early tutorials on the Sequelieze website.
I installed the latest sequelize and mysql with the following command.
$ npm install mysql
$ npm install sequelize
I have tried a lot of similar examples and always get the same error.
The libraries are working because other examples work fine, i could create tables in the database and get data from it but the authenticate function always fails.
Thanks! ;)
Authenticate returns a Promise in the later versions of sequelize:
https://github.com/sequelize/sequelize/blob/2.0/lib/sequelize.js#L939
Read the bluebird documentation here as it is quite useful:
https://github.com/petkaantonov/bluebird/blob/master/API.md
Something like this should work (make sure you check for connection errors...this is just a simple example):
var Sequelize = require('sequelize');
var sql = new Sequelize('DB', 'UNAME', 'PASS', {
host: 'localhost',
port: 3306,
dialect: 'mysql'
});
var test = sql.authenticate()
.then(function () {
console.log("CONNECTED! ");
})
.catch(function (err) {
console.log("SOMETHING DONE GOOFED");
})
.done();
Hi sequelize changed their auth scheme in latest release.. Please revert back to older version and try it
you were right!! ;)
I just remove sequelize and then reinstall an old veriosn:
npm install sequelize#1.7.0
and it works!!
I didn't found any info about that... Shouldn't they warn users from deprecated or modified functions ?¿?...
THANKS!! ;)
I suspect you're looking for
Sequelize.authenticate().complete(...)
instead of
Sequelize.authenticate.complete(...)
Sequelize.authenticate is a function that returns a promise. It's not an object with a .complete() method. If you don't execute it, no promise will be returned. If no promise is returned, you can't run .complete() on the promise.
Hope this helps you out.
Here is some documentation on Promises from the Mozilla Development Network.
Uninstall the sequelize module which is installed in your system and install this version using
npm install sequelize#1.7.0
Check the models folder and make sure it contains proper files
I'm new to Node.js and I'm trying to get a Flickr API working on my local machine:
https://github.com/ciaranj/flickrnode
I have installed the flickr module with npm install flickr.
The simplest call is:
var FlickrAPI= require('flickr').FlickrAPI;
var sys= require('sys');
var flickr= new FlickrAPI(your_api_key_here);
// Search for photos with a tag of 'badgers'
flickr.photos.search({tags:'badgers'}, function(error, results) {
sys.puts(sys.inspect(results));
});
I've changed 'sys' to 'util' as node prompted me to and added my api key so I'm calling:
var FlickrAPI= require('flickr').FlickrAPI;
var sys= require('util');
var flickr= new FlickrAPI('...');
// Search for photos with a tag of 'badgers'
flickr.photos.search({tags:'badgers'}, function(error, results) {
sys.puts(sys.inspect(results));
});
Running node myfile.js, I get:
var flickr= new FlickrAPI('a513719086ba8c3a28d2c7726939b58e');
^
TypeError: undefined is not a function
at Object.<anonymous> (/home/charm/ciaranj-flickrnode-8a9d85f/lib/simple.js:3:13)
at Module._compile (module.js:446:26)
at Object..js (module.js:464:10)
at Module.load (module.js:353:31)
at Function._load (module.js:311:12)
at Array.0 (module.js:484:10)
at EventEmitter._tickCallback (node.js:190:38)
Does anyone know how I overcome this problem?
Thanks!
npm install flickr installs https://github.com/sujal/node-flickr, not the one you're looking for. How to install a node.js module without using npm? explains how to install node packages manually