Node project works locally but fails when installing via NPM? - javascript

I have this straightforward node project, with a main.js file when I run it locally node main.js it works fine. But when I do an npm install -g cli-tweet and then try to run it, it outputs this error :
/home/USER/.npm-global/bin/tweet: 1: /home/USER/.npm-global/bin/tweet: Syntax error: "(" unexpected
The package.json looks something like this :
{
"name": "cli-tweet",
"main": "main.js",
"bin": {
"tweet": "main.js"
},
[...]
}
Any idea on how to fix this ?
Edit 1:
The code for main.js
var OAuth = require('oauth').OAuth,
colors = require('colors'),
Twitter = require('twitter'),
fs = require('fs'),
get_args = require('cli-pipe');
var CONFIG_FILE = '.tweet.json',
REQUEST_TOKEN_URL = 'https://api.twitter.com/oauth/request_token',
ACCESS_TOKEN_URL = 'https://api.twitter.com/oauth/access_token',
OAUTH_VERSION = '1.0', HASH_VERSION = 'HMAC-SHA1';
var key = "XYZ",
secret = "XYZ", tweetText;
function getAccessToken(oa, oauth_token, oauth_token_secret, pin) {
oa.getOAuthAccessToken(oauth_token, oauth_token_secret, pin,
function (error, oauth_access_token, oauth_access_token_secret, results2) {
if (error && parseInt(error.statusCode) == 401) {
throw new Error('The pin number you have entered is incorrect'.bold.red);
}
var keys = {
'ACCESS_TOKEN_KEY': oauth_access_token,
'ACCESS_TOKEN_SECRET': oauth_access_token_secret
};
fs.open(CONFIG_FILE, "wx", function (err, fd) {
try {
fs.close(fd, function (err) {
});
} catch (e) {
}
});
fs.writeFileSync(CONFIG_FILE, JSON.stringify(keys));
console.log('Try echo "test" | cli-tweet'.cyan);
process.exit(1);
});
}
function getRequestToken(oa) {
oa.getOAuthRequestToken(function (error, oauth_token, oauth_token_secret, results) {
if (error) {
throw new Error(([error.statusCode, error.data].join(': ')).bold.red);
} else {
console.log(('https://twitter.com/oauth/authorize?oauth_token=' + oauth_token).underline.blue)
console.log('Enter the pin number here:'.bold.yellow);
var stdin = process.openStdin();
stdin.on('data', function (chunk) {
var pin = chunk.toString().trim();
getAccessToken(oa, oauth_token, oauth_token_secret, pin);
});
}
});
}
function tweet(userTokens) {
var client = new Twitter({
consumer_key: key,
consumer_secret: secret,
access_token_key: userTokens.oauth_access_token,
access_token_secret: userTokens.oauth_access_token_secret
});
console.log("Tweet :" + tweetText.bold.cyan);
if (tweetText.length > 0) {
client.post('statuses/update', {status: tweetText}, function (error, tweet, response) {
if (error) {
console.log("Error :" + JSON.stringify(error));
}
process.exit(1);
});
} else {
console.log("Pipe a tweet".bold.red);
}
}
var isConfig = process.argv[2];
if (isConfig === undefined || isConfig.toLowerCase() != "config") {
try {
var contents = fs.readFileSync(CONFIG_FILE).toString(), tokens = JSON.parse(contents);
} catch (e) {
console.log("Error: Try running 'tweet config' command".bold.red);
}
if (tokens != undefined && (tokens.ACCESS_TOKEN_KEY != undefined && tokens.ACCESS_TOKEN_SECRET != undefined)) {
try {
get_args(function (args) {
tweetText = args[2];
tweet({
"oauth_access_token": tokens.ACCESS_TOKEN_KEY,
"oauth_access_token_secret": tokens.ACCESS_TOKEN_SECRET
});
});
} catch (e) {
console.log("Error: Unexpected error while tweeting".bold.red);
}
} else {
console.log("Try running 'cli-tweet config' command".bold.red);
}
} else {
var oa = new OAuth(REQUEST_TOKEN_URL, ACCESS_TOKEN_URL, key, secret, OAUTH_VERSION, 'oob', HASH_VERSION);
getRequestToken(oa);
}
Edit 2 :
Running the code like this: node /home/USER/.npm-global/lib/node_modules/cli-tweet/main.js seems to work

1) Add folder bin
2) Add file bin/tweet with
#!/usr/bin/env node
require('../main.js');
3) change package.json
"bin": {
"tweet": "./bin/tweet",
}

Related

Unable to switch user to root using Node.js ssh2 module

Trying to SSH to a server and able to. However, when I try to run sudo command it prompts me to enter the password of the userid mentioned. How do I prevent any keyboard interruption and hardcode the password so it doesn't prompt for password.
server.js
const { Client } = require('ssh2');
const conn = new Client();
conn.on('ready', () => {
console.log('Client :: ready');
conn.exec('sudo ls -lrt',{ stdin: 'password\n', pty: true }, (err, stream) => {
if (err) throw err;
stream.on('close', (code, signal) => {
console.log('Stream :: close :: code: ' + code + ', signal: ' + signal);
conn.end();
}).on('data', (data) => {
console.log('STDOUT: ' + data);
}).stderr.on('data', (data) => {
console.log('STDERR: ' + data);
});
});
}).connect({
host: 'hostname',
port: 22,
username: 'user1',
password: 'password'
});
The prompt I get:
STDOUT: [sudo] password for user1:
STDOUT:
sudo: timed out reading password
The below code works for me.
const Client = require('ssh2').Client;
const conn = new Client();
const encode = 'utf8';
const connection = {
host: 'hostname.foo.com',
username: 'iamgroot',
password: 'root#1234'
}
conn.on('ready', function() {
// Avoid the use of console.log due to it adds a new line at the end of
// the message
process.stdout.write('Connection has been established');
let password = 'root#1234';
let command = '';
let pwSent = false;
let su = false;
let commands = [
`ls -lrt`,
`sudo su - root`,
`ls -lrt`
];
conn.shell((err, stream) => {
if (err) {
console.log(err);
}
stream.on('exit', function (code) {
process.stdout.write('Connection closed');
conn.end();
});
stream.on('data', function(data) {
process.stdout.write(data.toString(encode));
// Handles sudo su - root password prompt
if (command.indexOf('sudo su - root') !== -1 && !pwSent) {
if (command.indexOf('sudo su - root') > -1) {
su = true;
}
if (data.indexOf(':') >= data.length - 2) {
pwSent = true;
stream.write(password + '\n');
}
} else {
// Detect the right condition to send the next command
let dataLength = data.length > 2;
let commonCommand = data.indexOf('$') >= data.length - 2;
let suCommand = data.indexOf('#') >= data.length - 2;
console.log(dataLength);
console.log(commonCommand);
console.log(suCommand);
if (dataLength && (commonCommand || suCommand )) {
if (commands.length > 0) {
command = commands.shift();
stream.write(command + '\n');
} else {
// su requires two exit commands to close the session
if (su) {
su = false;
stream.write('exit\n');
} else {
stream.end('exit\n');
}
}
}
}
});
// First command
command = commands.shift();
stream.write(command + '\n');
});
}).connect(connection);

How to FORK a repository inside aws codecommit using javascript from lambda?

I'm doing a implementation, and I need to fork a git repository into a codecommit repository using lambda and javascript. Create or update a file in the repository I can do.
What I need to know to fork a github repository (or a codecommit repository) for another repository inside codecommit?
I am showing the full code, because it is needed to undestand what I already do.
'use strict';
var AWS = require("aws-sdk");
var codecommit = new AWS.CodeCommit({ apiVersion: '2015-04-13' });
exports.handler = (event, context, callback) => {
event.Records.forEach((record) => {
console.log('Stream record: ', JSON.stringify(record, null, 2));
if (record.eventName == 'INSERT') {
var name = JSON.stringify(record.dynamodb.NewImage.name.S).replace(/[^a-z0-9áéíóúñü \.,_-]/gim,"");
var version = JSON.stringify(record.dynamodb.NewImage.version.S);
var data = JSON.stringify(record.dynamodb.NewImage.data.S);
var params = { repositoryName: name };
codecommit.getRepository(params, function(err, response) {
if (err) {
console.log(err, err.stack);
if(err.code == 'RepositoryDoesNotExistException') {
params.repositoryDescription='Repository ' + name;
codecommit.createRepository(params, function(err, response) {
if (err) {
console.log(err, err.stack);
} else {
console.log(response);
prepareCommit(name,version, data);
}
});
}
} else {
console.log('response repository: ', response);
prepareCommit(name, version, data);
}
});
}
});
callback(null, `Successfully processed ${event.Records.length} records.`);
};
function prepareCommit(name, version, data) {
var params = {
branchName: 'master',
repositoryName: name
};
codecommit.getBranch(params, function(err, response) {
if (err) {
console.log(err);
if (err.code='BranchDoesNotExistException') {
doCommit(name, version, '' + data, '');
}
} else {
console.log('response branch: ', response);
doCommit(name, version, '' + data, '' + response.branch.commitId);
}
});
}
function doCommit(name, version, data, parentCommitId) {
var params = {
branchName: 'master',
fileContent: Buffer.from(JSON.parse(data)) || '',
filePath: 'data/structure.json',
repositoryName: name,
commitMessage: 'generated by lambda stream ' + version,
email: '<email here>',
fileMode: 'NORMAL',
name: '<name here>'
};
if (parentCommitId != '') {
params.parentCommitId = parentCommitId;
}
codecommit.putFile(params, function(err, response) {
if (err) {
console.log(err, err.stack);
} else {
console.log(response);
}
});
}
This code receive a data from STREAM/DynamoDB and check if the repository exist, if not, a new is created and put a json file structure.json inside data/ folder.
I need fork a github or a codecommit repository on create inside a new repository.

How to return a documentDB document with Azure functions?

I created an azure function as well as a documentDB database with a users collection, however, I am stuck at connecting the two of them to each other. I want to just send a username and the function queries the database then returns the user with that unique username.
I am using node js. Any ideas?
Thanks
First of all, you'd need to install the documentdb module via npm. Use the following command:
npm install documentdb --save
After that, you've finished setting up. Now you can start writing some code to query the collection in the database. The following is an example of querying a family collection with Azure HTTP-trigger function.
The folder structure:
node_modules/
.gitignore
config.js
function.json
index.js
package.json
CONFIG.JS
var config = {}
config.endpoint = "https://<documentdb name>.documents.azure.com:443/";
config.primaryKey = "<primary key>";
config.database = {
"id": "FamilyDB"
};
config.collection = {
"id": "FamilyColl"
};
module.exports = config;
INDEX.JS
var documentClient = require("documentdb").DocumentClient;
var config = require("./config");
var databaseUrl = `dbs/${config.database.id}`;
var collectionUrl = `${databaseUrl}/colls/${config.collection.id}`;
var client = new documentClient(config.endpoint, { "masterKey": config.primaryKey });
module.exports = function (context, req) {
context.log('JavaScript HTTP trigger function processed a request.');
if (req.query.name || (req.body && req.body.name)) {
var name = req.query.name || req.body.name;
queryCollectionByName(name).then((result) => {
context.log('result: ', result);
res = {
body: "Result: " + JSON.stringify(result)
};
context.done(null, res);
}, (err) => {
context.log('error: ', err);
res = {
body: "Error: " + JSON.stringify(err)
};
context.done(null, res);
});
}
else {
res = {
status: 400,
body: "Please pass a name on the query string or in the request body"
};
context.done(null, res);
}
};
function queryCollectionByName(name) {
return new Promise((resolve, reject) => {
client.queryDocuments(
collectionUrl,
`SELECT VALUE r.children FROM root r WHERE r.lastName = "${name}"`
).toArray((err, results) => {
if (err) reject(err)
else {
resolve(results);
}
});
});
};
Tested result:
For more details, please refer to https://learn.microsoft.com/en-us/azure/documentdb/documentdb-nodejs-get-started.

Exporting Mysql Connection in nodeJS

In my database.js I have
var Mysql = require('Mysql');
var Jwt = require('jsonwebtoken');
var bcrypt = require('bcrypt');
var supersecretkey = 'JMDub_Super_Secret_key';
var config = require('./config');
var signupErrors = require('./Signuperrors.js');
var sucessMsg = require('./SucessMessages.js');
var App_errors = require('./error.js');
var query = require('./queryDB.js');
var connection = Mysql.createConnection({
"host": "******",
"user": "****",
"password": "***",
"database": "***"
});
connection.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('connected as id ' + connection.threadId);
});
//Sign Up Methods
var createUser = function createwithCredentails(post,callback) {
bcrypt.hash(post.password, 10, function(err, hash){
//console.log('Cache Hash : +',hash);
var createUserQuery = connection.query('INSERT INTO users SET ?',{"email":post.email,"password":hash,"username":post.username},function(err,result){
if (err) {
if (err.code == 'ER_DUP_ENTRY') {
//console.log(err.code);
callback(signupErrors.error_5000);
}
else callback(App_errors.error_1003);
}
if (result) {
callback(sucessMsg.success_signup);
}
});
});
}
//connection.query('SELECT * FROM Users Where Username = '' AND Password = ''');
var validateUser = function ValidateUserWithUserNameAndPassword(post,callback) {
var UserCheckQuery = connection.query('SELECT * FROM users WHERE email="'+post.email+'"',function(err, results, fields) {
if (err){
console.log(err);
callback(App_errors.error_1000);
}
if (results.length == 1) {
//console.log(results[0].password,post.password);
var givenPassword = post.password;
var DBhash = results[0].password;
bcrypt.compare(givenPassword, DBhash,function(err, res) {
if (res) {
console.log('Password matched');
var token = Jwt.sign({"email":post.email,"username":post.username},supersecretkey, {
expiresIn: 60*60*5 // expires in 5 hours
});
callback({
message:{
"success":1,
"description":"sucessfully logged in - please cache the token for any queries in future",
"environment":"test",
"errorCode":null
},
"token":token
});
}
if (!res) {
console.log('password doesnt match');
callback(signupErrors.error_6000);
}
if (err) {
console.log('Error Comparing Passwords');
callback(App_errors.error_1004);
}
});
}
else{
callback(signupErrors.error_6000);
}
});
};
var isauthenticate = function isauthenticated(post,route,callback) {
if (post.headers.token) {
Jwt.verify(post.headers.token, supersecretkey, function(err, decoded) {
if (decoded) {
//console.log(decoded);
//From this part the user is Sucessully Authenticated and autherization params can be extracted from token if required
//Write Business Logic in future as per the requirement
//Operation 1 - Update Profile
//Profile Details consists of {1.first name 2.last name 3. profile pictur(base 64 encoded) 4.further settings in future that can be added to DB if required}
if (route == '/update-profile') {
query.updateProfile(connection,decoded.email,post.body,function(response) {
callback(response);
});
}
//callback({"message":"is a valid token"});
}
if (decoded == null) {
console.log('is not a valid token');
//callback(App_errors.error_1000);
}
if (err) {
console.log('error verifying token');
callback(App_errors.error_1000);
}
});
}
else{
callback(App_errors.error_1001);
}
};
module.exports = {
validateUser:validateUser,
createUser:createUser,
isauthenticate:isauthenticate,
connection:connection
}
I am exporting connection object to queryDB.js file. But when I try to log the exported connection object I get undefined object. Why is this happening?
When I pass connection object as function argument, everything works fine. Not sure why?
below is queryDB.js file
var errors = require('./error.js')
var Dbconnection = require('./Database.js').connection;
var updateProfile = function profiledata(connection,email,data,callback) {
console.log(Dbconnection);
if ((!data)|| (Object.keys(data).length < 1)) {
//console.log(data);
callback(errors.error_1001);
}
else{
callback({"message":"update Sucesss"});
//console.log(connection);
//var updateData = mapProfileDataTomodel(data);
//console.log(updateData);
connection.query('SELECT * FROM users WHERE email = "'+email+'"',function(err, result,feilds) {
if (err) throw err;
if (result) {
console.log(result);
}
});
}
}
var mapProfileDataTomodel = function mapProfileDataTomodel(data) {
var profileDataModel = {};
for (var key in data) {
//console.log('looping and mapping data');
if (data.firstname) {
profileDataModel.firstname = data.firstname;
}
if (data.lastname) {
profileDataModel.lastname = data.lastname;
}
if (data.profilepic) {
profileDataModel.profilepic = data.profilepic;
}
}
return profileDataModel;
}
module.exports = {
updateProfile:updateProfile
}
I have commented out connection object log via function arguments.
So, Why I am unable to get the connection object that is exported? But I used the same exported connection object in my app.js file. It did work fine there.

Upload images to twitter API from node.js

I'm attempting to post an image onto the twitter api, v1.1
I've tried just about all the example out there, and nothing seems to be able to post it.
include Posting images to twitter in Node.js using Oauth
I'm using the oauth library mentioned there, and I also had jsOauth, which I thought I'd give a shot according to https://gist.github.com/lukaszkorecki/1038408
Nothing has worked, and at this point I'm starting to lose hope on whether I can even do this.
function postStatusWithMedia(status, file) {
var err = new Object();
if(fs.existsSync(file) === false) {
err.message = "File not found :(";
parseTwitterError(err);
} else {
var oauth = OAuth(options = {
"consumerKey": consumer_key,
"consumerSecret": consumer_secret,
"accessTokenKey": access_token,
"accessTokenSecret": access_token_secret
});
callbacks = {
onSuccess : function() {
console.log('upload worked!')
},
onFailure : function() {
console.log('upload failed!');
console.dir(arguments);
}
},
uploadData = {
'status' : status,
'media' : Base64.encode(fs.readFileSync(file))
};
oauth.post('https://api.twitter.com/1.1/statuses/update_with_media.json',uploadData, callbacks.onSuccess, callbacks.onFailure);
return false;
}
}
If it can't be done, can you please explain why?
Otherwise, anything that could lead me to the right direction would be great.
var fs = require('fs');
var request = require('request');
var FormData = require('form-data');
var utf8 = require('utf8');
// Encode in UTF-8
status = utf8.encode(status);
var form = new FormData();
form.append('status', status)
form.append('media[]', fs.createReadStream(file));
// Twitter OAuth
form.getLength(function(err, length){
if (err) {
return requestCallback(err);
}
var oauth = {
consumer_key: consumer_key,
consumer_secret: consumer_secret,
token: access_token,
token_secret: access_token_secret
};
var r = request.post({url:"https://api.twitter.com/1.1/statuses/update_with_media.json", oauth:oauth, host: "api.twitter.com", protocol: "https:"}, requestCallback);
r._form = form;
r.setHeader('content-length', length);
});
function requestCallback(err, res, body) {
if(err) {
throw err;
} else {
console.log("Tweet and Image uploaded successfully!");
}
}
I ended up using request and node-form-data to manually construct a multipart/form-data request and send it with the status request, utf8 was for encoding the status into UTF-8, not doing so caused issues with '<3' and other characters.
I have not tested these code.Its from my colleague.sure the code is working.
Perhaps this will help.
//twitter_update_with_media.js
(function() {
var fs, path, request, twitter_update_with_media;
fs = require('fs');
path = require('path');
request = require('request');
twitter_update_with_media = (function() {
function twitter_update_with_media(auth_settings) {
this.auth_settings = auth_settings;
this.api_url = 'https://api.twitter.com/1.1/statuses/update_with_media.json';
}
twitter_update_with_media.prototype.post = function(status, imageUrl, callback) {
var form, r;
r = request.post(this.api_url, {
oauth: this.auth_settings
}, callback);
form = r.form();
form.append('status', status);
return form.append('media[]', request(imageUrl));
};
return twitter_update_with_media;
})();
module.exports = twitter_update_with_media;
}).call(this);
next file
//upload_to_twitter.js
var tuwm = new twitter_update_with_media({
consumer_key: TWITTER_OAUTH_KEY,
consumer_secret: TWITTER_OAUTH_SECRET,
token: access[0],
token_secret: access[1]
});
media_picture.picture = imageURL;
if (media_picture.picture) {
console.log('with media upload');
request.head(media_picture.picture,
function (error, response, body) {
if (!error && response.statusCode == 200) {
var image_size = response.headers['content-length'];
if (image_size > 2000000) { // 2mb max upload limit
console.log('greater than 2mb');
sendMessageWithoutImage(err, req, res, next, twit, wallpost, access);
} else {
console.log('less than 2mb');
console.log('twitter text', content);
tuwm.post(content, media_picture.picture, function(err, response) {
if (err) {
console.log('error', err);
return next(err);
}
error_parse = JSON.parse(response.body);
console.log('with media response', response.body);
if (error_parse.errors) {
console.log('have errors', error_parse);
res.json({
status: 500,
info: error_parse.errors[0].code + ' ' + error_parse.errors[0].message
});
} else {
res.json({
status: 200,
info: "OK",
id: response.id
});
}
});
}
}
});

Categories

Resources