Create a CLI interface with Node own commands not working - javascript

Currently I am following the following tutorial
The tutorial basically is meant to create a node cli that allow me to CRUD contacts directly on the cli.
I want to do it without mongoose, since what I need is to perform cli commands that does requests to the server to extract data, but that is other history, just to explain that I do not use mongoose here. The first step worked well, basically if I do: node contact.js -- help, it calls the help command on my contact.js file.
The issue comes when I want to take out the node command, I basically want to call it like that, contact --help. That is not working, I used yarn link and followed the instructions on the tutorial, so what is wrong? Any help?
Here is what I did so far:
package.json
{
"name": "contacto",
"version": "1.0.0",
"main": "index.js",
"preferGlobal": true,
"bin": "./contact.js",
"license": "MIT",
"dependencies": {
"commander": "^2.15.1",
"inquirer": "^5.2.0",
"mongoose": "^5.0.12"
}
}
contact.js
#!/usr/bin/env node
/**
* We build a cli that is responsable to interact with the IPMA service, to filter any option, for options we mean: Temperature
* eartquake activity and another possible options, the next argument will be the zone(city),
*/
const program = require('commander');
program
.version('0.0.1')
.description('Contact management system');
program
.command('addContact <firstame> <lastname> <phone> <email>')
.alias('a')
.description('Add a contact')
.action((firstname, lastname, phone, email) => {
console.log(firstname,lastname,phone,email);
});
program.parse(process.argv);

The executable is created based on the package name, not on the name of the folder or the file.
As you have defined in the package.json, the name of the module is contacto (mind the 'o' at the end). This is the global executable name after you run the command yarn link.
The right way to execute the CLI in this case is: contacto --help

Related

Node.JS export ES Object into NPM package?

I have an ES5 object/function that I'm trying to use inside an NPM package. That object is in a namespace such as
MY_NAMESPACE.myObject = function(){...}
where MY_NAMESPACE is just an object. For the web, I'd just link a JS file where the object/function is and then do
let whatever = new MY_NAMESPACE.myObject();
I have saved the source as my_function.js.
I created a npm package like so, in order to install it in my app
{
"name": "whatever",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "whatever",
"license": "Apache-2.0",
"exports" :{
"./my_function.js" : "./my_function.js"
}
}
When I install the package locally, I can see that my_function.js is in node_modules/whatever
How can I now reference/import my_function.js inside my app, then be able to call
let whatever = new MY_NAMESPACE.myObject();
Some of the awful Node.JS documentation mentions .mjs files to add ES modules but can't find examples/tutorials... I'm also trying to not add anything like module.exports to the my_function.js because that file is updated constantly and used in a web/front end environment as well.
So basically, I'm trying to attach a .js file inside a NPM package and would like to have its content available in my app. I'm hoping that, adding something to the index.js of the package would render the objects declared in the file, available across my app... I just don't know where to go from here.
One pattern to expose the function would be using module.exports like this:
# my_function.js
MY_NAMESPACE = {};
MY_NAMESPACE.myObject = function(){...};
module.exports = MY_NAMESPACE;
And then it can be consumed by another module in the same directory as:
# consumer JS file
let MY_NAMESPACE = require('./my_function');
let test = new MY_NAMESPACE.myObject();
If you really want to package up my_function.js in a separate node.js package (for example, if you need to share it between projects), there are a few additional steps to take. This documentation is a good starting point.

Google cloud functions :: cant use 'require' statements

Issue
When I include any 'require' statements in a google cloud function, I get the warning: "Function is active, but the last deploy failed"
Solution ?
I'm pretty sure I need to include dependencies in the package.json file, but I don't know what dependencies to include, or how to write that.
Background
I've built an android app in Java and I'm trying to integrate stripe payments. Stripe requires me to have a server handle the requests, but I'm trying to use google cloud functions instead (so I don't have to pay / manage a server).
I'm trying to follow this example, but it's not working. The author didn't include the package.json file and I'm not sure what dependencies to put in there. I've never written java script before, my background is in python, c++, java.
I've looked at this tutorial from google as well as the google docs on writing cloud functions. I've also searched S.O. and can't find a solution. The problem may be that I'm not a javascript developer. I'm trying to just plug and play someone else's code to make one specific part of my android (java) app work.
Troubleshooting
To troubleshoot, I used the "helloWorld" example provided by google. The Hello World function works find by itself. If I add any of these three require statements at the top, I get the warning: "Function is active, but the last deploy failed"
Code
-- index.js
var app = require('express')();
var http = require('http').Server(app);
var stripe = require('stripe')(
"your_stripe_key"
);
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
//initiate a one-off charge for a customer
exports.chargeCustomer = app.get(".../charge/:customerid/:token/:amount", function chargeCustomer (req,res){
stripe.charges.create({
customer: req.params.customerid,
source: req.params.token,
currency: 'usd',
amount:req.params.amount
},function(err, charge) {
if(err) {
return res.send(JSON.stringify(err));
}
res.send(JSON.stringify(charge));
});
});
-- package.json
{
"name": "sample-http",
"version": "0.0.1"
}
Notes
If you know what I'm doing wrong, please remember I've never written javascript. I don't think I'm asking a duplicate question, I've searched, but its possible the answer is in another question and I'm just not understanding it because I've never written javascript.
I wrote the repo that you referenced in your question above. The problem is that you are not formatting your package.json file correctly.
When you deploy your functions, you will need to deploy your index file and a corresponding package.json. You can deploy either through command line, or by simply using the Google in-line editor in the Cloud Functions product.
The package.json file specifies the dependencies that your code needs to run. Basically, your index file needs to know which 3rd party libraries to require for it's functionality. You will notice in my example code below includes a small node for "dependencies", which will tell Google Cloud Functions which packages to install with your code.
The specific index file you reference is creating a charge via Stripe. I use a variation of this code in many production products, and the package.json file looks like this:
{
"name": "createCharge",
"version": "1.0.0",
"description": "create and charge in Stripe",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "Your Name",
"license": "ISC",
"dependencies": {
"express": "^4.14.0",
"stripe": "^4.4.0",
"body-parser": "~1.13.3",
"async": "^2.0.1",
"promise": "^7.1.1"
},
"engines": {
"node": "4.1.1"
},
"repository": {
"type": "git",
"url": "<path/to/your/repo.git>"
}
}
Also, just so that you are aware, the "repository" chunk of the above javascript is not required, so if you don't have a hosted repo for this specific function, feel free to delete it.
Hope this helps!
Here is an example with a package.json, it's mentioned in this documentation. I will past an example of its contents:
{
"nyc": {
"exclude": [
"build/src/apis",
"build/test"
]
},
"license": "Apache-2.0",
"dependencies": {
"google-auth-library": "^1.1.0",
"qs": "^6.5.1",
"string-template": "1.0.0",
"uuid": "^3.1.0"
},
...
}
also consider reading npm.js' documentation as package.json is generic and isn't Cloud Function specific.

How do I use the ES6 import function with a symbolic path to the source file?

I am trying to understand the ES6 import function better, and I need your help.
The Scenario
Let's assume that I have a subset of code within my application that is used frequently, and I arrange all that code into a folder so that it is together.
So now, in three separate files, I have something like the following (note: I'm using TypeScript, so the file names in the example end in '.ts'):
file0.ts:
import {AbstractCoreCommunicationClass} from '../../../core-packages/communication/abstract-core-communication'
file1.ts:
import {AbstractCoreCommunicationClass} from '../communication/abstract-core-communication'
file2.ts:
import {AbstractCoreCommunicationClass} from '../../../../../core-packages/communication/abstract-core-communication'
My Hope
It is my hope that I could clean up these references to something like this:
file0.ts:
import {AbstractCoreCommunicationClass} from '#my-communication-core/abstract-core-communication'
file1.ts:
import {AbstractCoreCommunicationClass} from '#my-communication-core/abstract-core-communication'
file2.ts:
import {AbstractCoreCommunicationClass} from '#my-communication-core/abstract-core-communication'
Things I have Tried
I know that in Laravel (a different framework) that modules can be created and loaded by editing one of the core loader definition files such as composer.json or the main config/app.php file.
I have looked for a similar kind of protocol that can be used in the package.json file to reference non-npm packages, but I have not found any such information. The closest information that I have found is a tutorial in which NPM explains how to use NPM private packages, which would accomplish the same goal as long as I want to pay $7/month for the rest of my life to have my package hosted on their servers.
There must be a way to handle this kind of package management locally, but I have not discovered what it is, and that is why I need YOUR help!
All help is appreciated. There are no wrong answers. Even a bad answer can sometimes point me in the right direction, so give me your thoughts and let's figure this out together so that everyone can benefit!
The solution is specific to the language and the environment. It's currently impossible to address this issue with ES modules alone.
TypeScript allows to specify paths configuration entry for path aliases.
Webpack allows to specify alias configuration entry for path aliases.
The same thing can be achieved in Rollup with a plugin.
NPM allows to specify local dependencies without a need for a repository. There's also a number of solutions for local NPM repositories, e.g. sinopia.
Given that there is TypeScript project that installs NPM dependencies and is being built with Webpack, any of listed solutions is applicable.
HOW TO USE LOCAL PACKAGES IN NPM
It turns out that NPM has a feature that allows me to do exactly what I need to do. I reread the package.json documentation after writing the question above and found that NPM now allows for a local file directory reference to a package.
How it looks in pacakge.json
I used npm to create the linkages (see next section), and then I inspected the package.json file to find the following:
"dependencies": {
"#angular/animations": "^4.0.0",
"#angular/common": "^4.0.0",
"#angular/compiler": "^4.0.0",
"#angular/core": "^4.0.0",
"#angular/forms": "^4.0.0",
"#angular/http": "^4.0.0",
"#angular/platform-browser": "^4.0.0",
"#angular/platform-browser-dynamic": "^4.0.0",
"#angular/router": "^4.0.0",
"core-js": "^2.4.1",
//###THIS IS MY NEW LINE###
"data-structures": "file:src/app/medface/data-structures",
"intl": "^1.2.5",
"ng2-cookies": "^1.0.12",
"rxjs": "^5.1.0",
"showdown": "^1.8.0",
"to-markdown": "^3.1.0",
"web-animations-js": "^2.2.5",
"zone.js": "^0.8.4"
},
Notice how the file: string prepends the source. I then designed a unit test to load one of the files from this directory using the name I assigned.
import {VisitDataStructure} from 'data-structures/visit';
describe( "The data structure package", ()=>{
fit("loads without failure and allows the user to import classes within the folder.", ()=>{
let visit = new VisitDataStructure();
expect(visit).not.toBeNull();
} );
} );
The test runs with flying colors!
(Note: the function fit is just like it, except it tells the testing system that it should "focus" only on that one test and ignore all the rest.)
How to achieve this using npm
To achieve this local package reference setup, several things must occur in order.
Step 1: Create a package using npm init
Navigate to the sub-folder in the terminal and type npm init (this assumes that you are already using npm, as I am).
Follow the on screen prompts to create your package.json file. The file will ask for a name, this name is how you will refer to the package within your system. In my case, I assigned the name 'data-structures' to the test package.
Step 2: Install the sub package using npm intall --save [pathToLocalFile]
From the root of your application, the same folder that holds the package.json file for your whole application, find the relative path to your new folder. In my case, it was src/app/medface/data-structures.
If your relative path is correct, then you should be able to use ls or dir to show a file at [relativePath]/package.json (linux/mac) or [relativePath]\package.json (windows)
Then run the command npm install --save [relativePath].
You will see npm do its thing. If it gives you an error, read the error and go back to step #1. (When I ran it the first time, I got an error and realized that I had to use npm init in the directory before I could install it).
Note: for the terminal command alternative, yes, you CAN use npm install -S [relativePath] -- it is the same command as above.
Step 3: Use your new package name in the code.
Now that it is installed, you can use the name you assigned anywhere within your code, and the package.json file will tell your pre-processor where to find the reference files.
GREAT WORK! Now go do some awesome coding!

DeprecationWarning process.EventEmitter is deprecated

Already applied require('events') but still the warning is keep showing, what is that i am doing wrong here? Why process.EventEmitter is keep showing up even its not used?
Node v6.7.0 it works, but v6.9.1 this is happening on CentOS 7.2
var pro = require('events');
var port = parseInt(config.server.port, 10);
var io = require('socket.io').listen(port); // This line is causing it???
Output Warning:
dev environment detected
info - socket.io started
(node:32708) DeprecationWarning: process.EventEmitter is deprecated. Use require('events') instead.
EDIT:
I used $ npm install
where package.json had following:
{
"name": "TEST",
"description": "TEST",
"version": "0.0.2",
"dependencies": {
"getconfig": "0.3.0",
"node-uuid": "1.2.0",
"socket.io": "0.9.16",
"yetify": "0.0.1"
},
"main": "test.js",
"repository": {
"type": "git",
},
"devDependencies": {
"socket.io-client": "0.9.16",
"precommit-hook": "0.3.10",
"tape": "^2.13.1"
},
"scripts": {
"test": "node test.js"
}
}
You may be using and old version of socket.io because in your code you don't use process.EventEmitter directly. If this program that you posted shows the warning then this is what could be the problem.
On my system the same program doesn't cause the problem - node 7.0.0 and socket.io 1.5.1 - but maybe you didn't include all of your code in your example (e.g. the config.server.port is not defined so you seem to have removed some portions of your code that may be relevant here).
You can see the version that you're using in:
node_modules/socket.io/package.json
See your own package.json and search for a line like:
"socket.io": "^1.4.8"
(like this line in one of my projects on GitHub) to see what version is installed with npm install and update the version if it's outdated. It's also possible that you have the socket.io module installed globally.
You can use David to let you know that you have outdated dependencies.
You can use Greenkeeper to help you keep your dependencies up to date.
(It's also good to add Snyk to let you know about vulnerabilities in your dependencies.)
Update
You posted your package.json and indeed you use an old version of socket.io:
"socket.io": "0.9.16",
so this exact version is installed when you run npm install. The current version is 1.5.1 - see:
https://www.npmjs.com/package/socket.io
You can change the version and rerun npm install. If the code is exactly the same as posted then you shouldn't need to change your code. If there is more code then see http://socket.io/docs/migrating-from-0-9/ for things that may need to be changed.
If you use CI tests, David and Greenkeeper, as I suggest above, then all of that (updating the version, testing if it still works etc.) would basically be done for you automatically.
If you use Snyk, as I also suggest above, then you'll know the version of socket.io that you're using has high-severity vulnerabilities, including Denial of Service and Remote Memory Exposure - that you now have in your code. See:
https://snyk.io/test/npm/socket.io/0.9.15
https://snyk.io/test/npm/socket.io/1.5.1
So as you can see, updating the socket.io dependency is important for more serious reasons than just the deprecation warning.

Unable to resolve parse-react in React Native project

I'm trying to include parse-react into my React Native project, but when running the app I'm getting the error in XCode and simulator:
Unable to resolve module ./lib/react-native/ParseReact.js from /Users/Corey/Work/example_app/node_modules/parse-react/react-native.js: Unable to find this module in its module map or any of the node_modules directories under /Users/Corey/Work/example_app/node_modules/parse-react/lib/react-native/ParseReact.js and its parent directories
I've included the two packages as such:
import Parse from 'parse/react-native';
import ParseReact from 'parse-react/react-native';
Looking in the node_modules/parse-react folder, the lib directory doesn't contain a react-native directory, but it does have the browser directory. I'm not sure if this is the problem or not, or how I'd go about getting that if it is.
I'm using react 0.14.7, react-native 0.21.0, parse 1.6.14, and parse-react 0.5.1.
I've had the same problem. I'm leaving my package.json here. Install accordingly, and you should be able to include parse modules into your project.
{
"name": "commonDemo",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start"
},
"dependencies": {
"parse": "^1.8.1",
"parse-react": "^0.5.0",
"react-native": "^0.20.0"
}
}
Let me know if this works. Ideally, you should be able to include parse modules into your project using latest react-native release. But if using parse is absolutely necessary for your project, use this package.json.
To call Parse.initialize() use this-
var Parse = require('parse/react-native');
To call cloud functions and other functionality, use this-
var ParseReact = require('parse/react-native').Parse;
Look at the parse-react github README page. It says it works with version 1.6.14 of parse. It also says that 1.7 and 1.8 breaks compatibility. I had the same problem and downgrading to 1.6.14 solved the issue.
npm install parse#1.6.14 --save

Categories

Resources