Npm install with success but nodejs cannot find module 'db' - node.js

This error is so common but although I searched a lot of similar questions I did not found a solution to my problem. I installed the module with no problems using "npm install db".
The "server.js" is in the same folder as"node_moludes" and NPM created a "db" folder inside "node_moludes" with all the content.
All NPM commands return success (install, link, list etc), I even added the module to my "package.json" and it also installs with no problem just using "npm install -d".
Despite it all, when I run the server, Nodejs can't find the 'db' module... any help?
nodejs version: 0.10.26
npm version: 1.4.3
server.js
var http = require('http'),
url = require('url'),
db = require('db');
var send = function(response, data){
response.writeHead(200, {
'Content-Type': 'text/plain',
'Access-Control-Allow-Origin': '*'
});
response.end(JSON.stringify({data: data}));
};
http.createServer(function (request, response) {
var query = url.parse(request.url, true).query;
if(query.set) {
db.set(query.set, query.val || '');
send(response, true);
} else if (query.get) {
db.get(query.get, function(data){
send(response, data);
});
} else send(response, query);
}).listen(80);
package.json
{
"name": "xxxxx",
"version": "0.0.1",
"author": "rafaelcastrocouto",
"repository": "git://github.com/rafaelcastrocouto/xxxxx",
"dependencies": {
"db": ">= 1.00.x"
},
"engine": "node >= 0.10.x"
}

It appears the db module was setup without following some Node.js norms. It doesn't contain an index.* file or specify a "main" setting in its package.json to direct Node otherwise.
You should be able to reference the main file within the package directly:
var db = require('db/db');

Related

Shopify node api context initalize errors out

I'm trying to make an app following these directions:
https://github.com/Shopify/shopify-node-api/blob/main/docs/getting_started.md
I have all the code configred and it looks like this:
// src/index.ts
import http from 'http';
import url from 'url';
import querystring from 'querystring';
import Shopify, { ApiVersion } from '#shopify/shopify-api';
require('dotenv').config();
const { API_KEY, API_SECRET_KEY, SCOPES, SHOP, HOST } = process.env
Shopify.Context.initialize({
API_KEY,
API_SECRET_KEY,
SCOPES: [SCOPES],
HOST_NAME: HOST.replace(/https?:\/\//, ""),
HOST_SCHEME: HOST.split("://")[0],
IS_EMBEDDED_APP: {boolean},
API_VERSION: ApiVersion.{version} // all supported versions are available, as well as "unstable" and "unversioned"
});
// Storing the currently active shops in memory will force them to re-login when your server restarts. You should
// persist this object in your app.
const ACTIVE_SHOPIFY_SHOPS: { [key: string]: string | undefined } = {};
async function onRequest(
request: http.IncomingMessage,
response: http.ServerResponse,
): Promise<void> {
const {headers, url: req_url} = request;
const pathName: string | null = url.parse(req_url).pathname;
const queryString: string = String(url.parse(req_url).query);
const query: Record<string, any> = querystring.parse(queryString);
switch (pathName) {
default:
// This shop hasn't been seen yet, go through OAuth to create a session
if (ACTIVE_SHOPIFY_SHOPS[SHOP] === undefined) {
// not logged in, redirect to login
response.writeHead(302, {Location: `/login`});
response.end();
} else {
response.write('Hello world!');
// Load your app skeleton page with App Bridge, and do something amazing!
}
return;
} // end of default path
} // end of onRequest()
http.createServer(onRequest).listen(3000);
Package JSON looks like this:
{
"name": "shopify-checkout-apit",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"dependencies": {
"#shopify/shopify-api": "^3.1.0"
},
"devDependencies": {
"#types/node": "^17.0.40",
"dotenv": "^16.0.1",
"typescript": "^4.7.3"
},
"scripts": {
"build": "npx tsc",
"prestart": "yarn run build",
"start": "node dist/index.js"
}
}
When I go to run the app with yarn start I get a ton of errors
PS C:\Users\kawnah\shopify-checkout-apit> yarn start yarn run v1.22.18
$ yarn run build $ npx tsc src/index.ts:17:27 - error TS1003:
Identifier expected.
17 API_VERSION: ApiVersion.{version} // all supported versions are
available, as well as "unstable" and "unversioned"
~
src/index.ts:18:1 - error TS1005: ',' expected.
18 }); ~
Found 2 errors in the same file, starting at: src/index.ts:17
error Command failed with exit code 2. info Visit
https://yarnpkg.com/en/docs/cli/run for documentation about this
command. error Command failed with exit code 2. info Visit
https://yarnpkg.com/en/docs/cli/run for documentation about this
command. PS C:\Users\kawnah\shopify-checkout-apit>
I have no idea what any of this means.
Typescript Error TS1003 when attempting to access object properties using bracket notation
Why does this trigger an Identifier Expected error in Typescript?
I tried deleting node modules and reinstalling but it didn't work.
How do you fix this?
the config needs to look like this
Shopify.Context.initialize({
API_KEY,
API_SECRET_KEY,
SCOPES: [SCOPES],
HOST_NAME: HOST.replace(/https?:\/\//, ""),
HOST_SCHEME: HOST.split("://")[0],
IS_EMBEDDED_APP: true,
API_VERSION: ApiVersion.October21 // all supported versions are available, as well as "unstable" and "unversioned"
});

Personality insight input var nodejs

var PersonalityInsightsV2 = require('watson-developer-cloud/personality-insights/v2');
var personality_insights = new PersonalityInsightsV2({
username: '<username>',
password: '<password>'
});
personality_insights.profile({
text: '<?php echo $_Session['description'];?>',
language: 'en' },
function (err, response) {
if (err)
console.log('error:', err);
else
console.log(JSON.stringify(response, null, 2));
});
It doesn't display anything. I have also done npm watson cloud and saved it, I have put my credentials and also forked it on git. What am I missing? I am a beginner but would love to use this on my page!
Here are the steps to run it locally, since you are a beginner I'll start from the beginning.
Create a new folder and name it whatever you want. Put these files in there.
Name the first file: index.js
fill in <YOUR-USERNAME>, <YOUR-PASSWORD>, and <YOUR-100-UNIQUE-WORDS> variables.
var express = require('express');
var app = express();
var http = require('http').Server(app);
var cfenv = require("cfenv");
var appEnv = cfenv.getAppEnv();
http.listen(appEnv.port, appEnv.bind);
var PersonalityInsightsV2 = require('watson-developer-cloud/personality-insights/v2');
var personality_insights = new PersonalityInsightsV2({
username: '<YOUR-USERNAME>',
password: '<YOUR-PASSWORD>'
});
personality_insights.profile({
text: "<YOUR-100-UNIQUE-WORDS>",
language: 'en' },
function (err, response) {
if (err)
console.log('error:', err);
else
console.log(JSON.stringify(response, null, 2));
});
Create another file and name it: package.json
put these contents in there
{
"name": "myWatsonApp",
"version": "1.0.0",
"description": "A Watson Personality Insights application",
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"dependencies": {
"cfenv": "^1.0.3",
"express": "^4.13.4",
"watson-developer-cloud": "^2.2.0"
}
}
open your terminal and cd to the root of your folder you just created.
Run the command: npm install
Then run the command npm start
Your application will then be running and you will see output from the personality insights call you made in index.js

Node registry path with electron-updater and Sinopia

I am currently working on an application running on Electron (former atom-shell), and trying to design a way to alert the user when a new update is available. To do this, I am using electron-updater in the way described in electron-updater-sample. I also configured Sinopia to be listening on http://localhost:4873/ (default behavior) and ran this commande line:
npm config set registry "http://localhost:4873"
I checked in the .npmrc file, the registry is properly set with the new value.
The problem I have is when I try to check for the update, I get this error message in console:
{ [HTTPError: Response code 404 (Not Found)]
message: 'Response code 404 (Not Found)',
code: undefined,
host: 'registry.npmjs.org',
hostname: 'registry.npmjs.org',
method: 'GET',
path: '/hacker-keyboard-electron',
statusCode: 404,
statusMessage: 'Not Found' }
So I believe I forgot something in the configuration of npm that makes the application listen to the regular path for npm rather than the Sinopia server. The question is what?
Please find below the code I am using:
foobar-generator
├── app
├── bower components
├── bower.json
├── index.html
├── index. js
├── main. js
├── nbproject
├── node modules
├── npm-debug.log
├── package.json
├── readme. md
└── sinopia
package.json
{
"name": "foobar-generator",
"version": "0.0.1",
"description": "A generator for foobar",
"main": "main.js",
"dependencies": {
"angular": "^1.4.7",
"bootstrap": "^3.3.5",
"chokidar": "^1.2.0",
"electron-debug": "^0.2.1",
"electron-packager": "^5.1.0",
"electron-plugins": "^0.0.4",
"electron-prebuilt": "^0.33.6",
"electron-rebuild": "^1.0.2",
"electron-updater": "^0.2.0",
"grunt": "^0.4.5",
"jquery": "^2.1.4"
},
"devDependencies": {},
"publishConfig": {
"registry": "http://localhost:4873/"
},
"registry": "http://localhost:4873/"
}
main.js
var appli = require('app');
var BrowserWindow = require('browser-window');
var updater = require('electron-updater');
var util = require('util');
// Report crashes to our server.
require('crash-reporter').start();
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
var mainWindow = null;
var loaded = false;
// Quit when all windows are closed.
appli.on('window-all-closed', function () {
// On OS X it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') {
appli.quit();
}
});
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
appli.on('ready', function () {
updater.on('ready', function () {
// Create the browser window.
mainWindow = new BrowserWindow({width: 800, height: 600});
// and load the index.html of the app.
mainWindow.loadUrl('file://' + __dirname + '/index.html');
mainWindow.openDevTools({detach: true});
mainWindow.on('closed', function () {
mainWindow = null;
});
});
updater.on('updateRequired', function () {
appli.quit();
});
updater.on('updateAvailable', function () {
if (mainWindow) {
mainWindow.webContents.send('update-available');
}
});
updater.start();
updater.check(function (err, results) {
if (err) {
return console.error(util.inspect(err));
}
console.log(results);
});
});
Do you guys see anything I could have forgotten/done wrong?
By reading the manual for npmrc (npm help npmrc), I have discovered the the .npmrc file is not unique. By configuring the registry the way I did, I only changed the per-user .npmrc. But there also should be such a file in your project root directory! It is in this one that you should configure the registry you want to use. Adding this file in project root directory solved the problem I was facing.
You should listen to error event.
Try this
updater.on('error', function (err) {
console.log(err);
});

grunt-contrib-connect - undefined is not a function for connect.static

I am trying to configure the grunt connect such a way that
For static pages it serves pages from src directory
web service calls are intercepted by middle-ware and static json is served.
While the web service calls are being mocked correctly the connect.static call ends up giving an error
TypeError: undefined is not a function
While I realize that the connect.static was provided in later versions of this module, I have already upgraded to a version later than that
Here is my package.json file
{
"name": "my-angular-seed-project",
"version": "1.0.0",
"description": "angular seed with only bower and grunt",
"main": "index.js",
"dependencies": {
},
"devDependencies": {
"bower": "^1.4.1",
"grunt": "^0.4.5",
"grunt-cli": "^0.1.13",
"grunt-contrib-connect": ">=0.10.0",
"grunt-contrib-jshint": "latest",
"grunt-contrib-uglify": "latest",
"grunt-contrib-watch": "latest",
"jshint-stylish": "^2.0.1"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
Here is the gruntfile.js
// Gruntfile.js
// our wrapper function (required by grunt and its plugins)
// all configuration goes inside this function
module.exports = function(grunt) {
var restEndPoints = {
"/restapi/users": {"GET":"json-files/users.get.json"},
"/restapi/users/login": {"GET":"json-files/users.get.json"},
"/restapi/users/john#gmail.com": {"GET":"json-files/users.get.john.json"},
"/restapi/nodes": {"GET":"json-files/nodes.get.json","PUT":"json-files/nodes.put.json","POST":"json-files/nodes.put.json"},
"/restapi/nodes/Node1": {"GET":"json-files/nodes.get.node1.json","DELETE":"json-files/nodes.delete.node1.json"},
"/restapi/services": {"GET":"json-files/services.get.json","PUT":"json-files/services.put.json","POST":"json-files/services.put.json"},
"/restapi/services/nginx": {"GET":"json-files/services.get.nginx.json","DELETE":"json-files/services.delete.nginx.json"},
"/restapi/commands": {"GET":"json-files/commands.get.json","PUT":"json-files/commands.put.json","POST":"json-files/commands.put.json"},
"/restapi/commands/pwd": {"GET":"json-files/commands.get.pwd.json","DELETE":"json-files/commands.delete.pwd.json"}
};
String.prototype.endsWith = function(suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1;};
// ===========================================================================
// CONFIGURE GRUNT ===========================================================
// ===========================================================================
grunt.initConfig({
// get the configuration info from package.json ----------------------------
// this way we can use things like name and version (pkg.name)
pkg: grunt.file.readJSON('package.json'),
// all of our configuration will go here
watch: {
},
// configure jshint to validate js files -----------------------------------
jshint: {
options: {
reporter: require('jshint-stylish') // use jshint-stylish to make our errors look and read good
},
// when this task is run, lint the Gruntfile and all js files in src
build: ['Gruntfile.js', 'src/**/*.js']
},
// configure connect to run server (on test/serve or example)
connect: {
server: {
options: {
port : 8000,
hostname : 'localhost',
base : 'src',
middleware: function (connect,options){return [
//Middleware #1 - for rest api calls
function restapiMiddleware(req, res, next) {
if (req.url.indexOf('restapi') > 0){
console.log(req.method+' request received for webservice api ['+req.url+']');
var match = false;
var json_file_to_serve = "";
var keys = Object.keys(restEndPoints);
keys.forEach(function(urlAsKey) {
if (req.url.endsWith(urlAsKey)) {
Object.keys(restEndPoints[urlAsKey]).forEach(function(httpMethodsAsKey) {
if (req.method == httpMethodsAsKey){
match = true;
json_file_to_serve = restEndPoints[urlAsKey][httpMethodsAsKey];
}
}); //forEach ends
}
}); //forEach ends
//no match with the url, move along
if (match == false) {
return next();
}
if (req.url.endsWith('/login')){
res.writeHead(200, { 'user-auth-token':'56f7997504b352cbf6ba6210409e423f5fdac49a','user-enc-email':'lJUXityStsKko/lPr9eJUc5fLFCV5kFm' });
}
//Finalize this response with json file
res.end(grunt.file.read(json_file_to_serve));
// if not restapi call then goto next middleware
// can we serve static right here ?
}else{
return next();
}
} // element/middleware one ends so comma just json objects this is awesome
,
//Middleware #2 for static page calls
function staticMiddleware(connect,options) {
connect.static(options.base);
//connect.static('src');
}
] // array ends
}
}
}
}
});
// ===========================================================================
// LOAD GRUNT PLUGINS ========================================================
// ===========================================================================
// we can only load these if they are in our package.json
// make sure you have run npm install so our app can find these
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.loadNpmTasks('grunt-contrib-watch');
//register the task
grunt.registerTask('serve', ['connect', 'watch']);
};
Am I missing something trivial here ?
Thanks #R4c00n & #Christian Fritz, I was going through the gruntfile of the grunt-contrib-connect and it uses the serveStatic call instead of connect.static and yes the module serve-static is part of grunt contrib connect's node_modules. So now a serveStatic(base.options) does wire the static files as well.
Here is the updated grunt file section (the serve static call has to be first though)
middleware: function (connect,options){return [
//statically serve pages from src directory
serveStatic('src'),
//Middleware #1 - for rest api calls
function restapiMiddleware(req, res, next) {
// middleware code
}];}

cloud9 crypto is not working at all been trying for days

I am trying to get a setup work with utils, the problem is it can not find the crypto module.
I have install utils and crypto using npm install then when I run my script
node server.js casper.js
I get this error
Error: Cannot find module 'crypto'
phantomjs://bootstrap.js:289
phantomjs://bootstrap.js:254 in require
/var/lib/stickshift/53452520e0b8cd1d870002e1/app-root/data/828422/node_modules/utils/utils.js:7
/var/lib/stickshift/53452520e0b8cd1d870002e1/app-root/data/828422/node_modules/utils/utils.js:117
/var/lib/stickshift/53452520e0b8cd1d870002e1/app-root/data/828422/node_modules/utils/utils.js:118
TypeError: 'undefined' is not a function (evaluating 'utils.inherits(Nightmare, Casper)')
/var/lib/stickshift/53452520e0b8cd1d870002e1/app-root/data/828422/node_modules/nightmarejs/lib/nightmareClient.js:21
/var/lib/stickshift/53452520e0b8cd1d870002e1/app-root/data/828422/node_modules/nightmarejs/lib/nightmareTest.js:16
why can it not find crypto. I have tried all different ways to get this working, but no luck
does any one have any ideas?
package.json file
{
"name": "chat-example",
"version": "0.0.0",
"description": "A chat example to showcase how to use `socket.io` with a static `express` server",
"main": "server.js",
"repository": "",
"author": "Mostafa Eweda <mostafa#c9.io>",
"dependencies": {
"async": "~0.2.8",
"express": "~3.2.4",
"socket.io": "~0.9.14",
"phantomjs": "*",
"casperjs": "*",
"nightmarejs": "*",
"utils": "*",
"casper": "*"
}
}
server.js
var nightmareJS = require('./node_modules/nightmarejs/lib/nightmare').nightmare('test');
nightmareJS.notifyCasperMessage = function(msg) {
if(msg.type == 'statement') {
console.log(msg.msg);
console.log("Nightmare Server says hello.");
}
else if(msg.type == 'dateQuestion') {
console.log(msg.msg);
var d = new Date();
nightmareJS.sendCasperMessage({ time: d.toString(), timeNow: d.getTime()});
}
}
casper.js
casper.start('http://www.google.com', function() {
this.test.assertTitle('Google', 'Google has the correct title');
this.sendMessageToParent({ type: 'statement', msg: 'Hello Nightmare.'})
})
casper.then(function() {
this.waitForMessageResponse({ type: 'dateQuestion', msg: 'What time is it?'}, 'time', function() {
var d = new Date();
this.echo('Nightmare thinks the time is: ' + this.lastDataReceived.time);
this.log('Nightmare thinks the time is: ' + this.lastDataReceived.time, 'debug');
this.test.assert(Math.abs(this.lastDataReceived.timeNow - d.getTime()) < 1000, "Nightmare and Casper's times are within 1000 seconds of each other");
})
});
casper.run(function() {
this.test.done();
});
and then i run the files using
node server.js casper.js
i am trying to get nightmarejs to work but utils cannot find crypto
please someone help i so need this to work

Resources