use nodejs in web site online - node.js

I have a web site online, on the disk of my freebox (https://www.free.fr/assistance/52.html).
On this web site, i have a page index.html with only one buton. I would like this buton to execute this file index.js :
const ewelink = require('ewelink-api');
/* instantiate class */
(async () => {
const connection = new ewelink({
email: 'XX',
password: 'XX',
region: 'eu'
});
/* Astrolabe id : 1001091c4b */
const status = await connection.setDevicePowerState('1001091c4b', 'toggle', 1);
console.log(status);
})();
This script is functional when i call it " node index.js" in the command line, but i have an issue by execute this js file on my page : "Uncaught ReferenceError: require is not defined".
I already saw topics on this but i don't want a localhost for my site, it's already on the web, isn't it ? Sorry i'm new, maybe it's a basic thing.
Thanks,
Thomas

Related

MongoDB Quick Start fails, keeps returning "null" on Terminal

Hi, I am self-learning MongoDB (with Node.js). Totally new to programming.
My first Node.js application doesn't return the MongoDB document like it supposed to.
What I want to achieve:
To work with the native MongoDB driver, and to complete the quick start procedure on MongoDB website: https://www.mongodb.com/docs/drivers/node/current/quick-start/
What I have tried so far:
Installed node & npm correctly;
Installed MongoDB#4.8 correctly;
Initialized all these via Terminal;
Set up Atlas, obtained connection string.
Still, when I put template (obtained from MongoDB quick start tutorial) into my server.js file, entered "npx nodemon app.js" to test, it returns: "null".
Here's code I put into server.js: (all account & password typed in correctly)
const { MongoClient } = require("mongodb");
// const uri = "mongodb://localhost:27017";
const uri = "mongodb+srv://<myClusterUsername>:<myPassword>#cluster0.fytvkcs.mongodb.net/?retryWrites=true&w=majority";
const client = new MongoClient(uri);
async function run() {
try {
const database = client.db('sample_mflix');
const movies = database.collection('movies');
// Query for a movie that has the title 'Back to the Future'
const query = { title: 'Back to the Future' };
const movie = await movies.findOne(query);
console.log(movie);
} finally {
// Ensures that the client will close when you finish/error
await client.close();
}
}
run().catch(console.dir);
As you can see, I also tried uri: localhost:27017, but output stay still on my Terminal: "null".
According to MongoDB, it was supposed to return such online sample doc:
{
_id: ...,
plot: 'A young man is accidentally sent 30 years into the past...',
genres: [ 'Adventure', 'Comedy', 'Sci-Fi' ],
...
title: 'Back to the Future',
...
}
Your help would be appreciated! Thanks very much!
you should open the folder in visual studio code like this :
enter image description here

Token passed to createTokenAuth is not a string : octokit, auth-token

I am trying to build a GitHub App and following the https://probot.github.io/docs/ and https://octokit.github.io/rest.js/v17#authentication. It is basically a nodejs app.
I have no experience working with nodejs or typescript and not even the probot framework.
The PRIVATE_KEY_PATH is in the .env file as follows:
PRIVATE_KEY_PATH=my-app.2020-04-03.private-key.pem
The .pem file is in the root directory of the project
The typeof prints string :
-------------TypeOf token ---- string
index.js
/**
* This is the main entrypoint to your Probot app
* #param {import('probot').Application} app
*/
const{Octokit} = require("#octokit/rest");
const{createAppAuth} = require("#octokit/auth-token");
console.log('PRIVATE_KEY',process.env.PRIVATE_KEY_PATH);
console.log('-------------TypeOf token ----', typeof process.env.PRIVATE_KEY_PATH)
const appOctokit = new Octokit({
authStrategy:createAppAuth,
auth:{
id:12345,
privateKey: process.env.PRIVATE_KEY_PATH,
// privateKey: 'token ${process.env.PRIVATE_KEY_PATH}'
}
});
I keep getting below error :
10:52:51.166Z ERROR probot: [#octokit/auth-token] Token passed to createTokenAuth is not a string
Not able to find much help on this topic over teh internet. I even tried navigating the code of octokit https://github.com/octokit/auth-token.js/blob/master/src/index.ts and it seems I am doing nothing wrong in my code.
There are not much resources to refer for issues for GitHub Apps or probot framework apart from the documentations. StackOverflow too ha just about 20-30 questions related to GitHub Apps or probot framework.
EDIT 1 : START
Running below code :
/**
* This is the main entrypoint to your Probot app
* #param {import('probot').Application} app
*/
const{Octokit} = require("#octokit/rest");
const{createAppAuth} = require("#octokit/auth-token");
console.log('PRIVATE_KEY',process.env.PRIVATE_KEY_PATH);
console.log('-------------TypeOf token ----', typeof process.env.PRIVATE_KEY_PATH)
produces a below error:
ERROR probot: appFn is not a function
TypeError: appFn is not a function
EDIT 1 : END
If you use Probot, you don't need to load your own #octokit/rest or any of the #octokit/auth-* packages, it's all built into Probot
Did you try the example code shown on https://probot.github.io/
module.exports = app => {
app.on('issues.opened', async context => {
const params = context.issue({
body: 'Hello World!'
})
await context.github.issues.createComment(params)
})
}
Probot will automatically read the contents of your .env file, look for the PRIVATE_KEY_PATH environment variable, read out the contents of the file at that location, and setup the JWT/installation authentication for you

Creating sub connections with azure-mobile-apps and NodeJS

I'm trying to create an API using nodeJS, express and azure-mobile-apps to do some data synchronisation between an Ionic3 mobile app (which use an SQLite local database) and a Microsoft SQL Database.
My API has to create a synchronisation connection for each mobile application. Each application will be linked to a distant database. For example, if user_01 wants to synchronise his data, he's going to be linked to his client_01 database. So each time it'll have to, the API will create a new process running on a different port.
here is an example : https://zupimages.net/up/19/36/szhu.png
The problem is that i'm not able to create more than one connection with azure-mobile-apps. The first one always works, but the second, third etc are still using the first connection that i have instantiated. I've looked into the app stack and everything seems fine.
Is that an issue with azure-mobile-app, or did I misunderstand something with express ?
Thanks for your responses !
var azureMobileApps = require('azure-mobile-apps');
var express = require('express');
module.exports = {
async createConnection(client) {
try {
let app = express();
mobileApp = azureMobileApps({
homePage: true,
swagger: true,
data: {
server: '****',
user: client.User,
password: client.Password,
port: '1443',
database: client.Database,
provider: 'mssql',
dynamicSchema: false,
options: {
encrypt: false
}
}
});
await mobileApp.tables.import('./tables');
await mobileApp.tables.initialize();
app.listen(global.portCounter);
app.use(mobileApp);
console.log(app._router.stack);
console.log('Listening on port ',global.portCounter);
global.portCounter++;
} catch (error) {
console.log(error);
}
}
}
It's working now. The thing is, it's impossible to do multiple connection with the azure-mobile-apps SDK for nodeJS.
I had to use worker-thread which seems to isolate the memory in a sub-proccess.
Hope it can help somebody one day

Skype Bot responding with empty body

I'm trying to get a Skype bot up and running based off of the echo example but I'm struggling to make a successful POST to my app. When I send a post to /v1/chat I get back a status of 201 (successful creation), and nothing in the body. My console.log does not print anything either, which leads me to believe that the botService.on('personalMessage', ...) function is not being run. Does anyone have any insight into how these POST requests should be formatted? I cannot seem to find anything in the documentation.
My code:
const fs = require('fs');
const restify = require('restify');
const skype = require('skype-sdk');
const botService = new skype.BotService({
messaging: {
botId: '28:<bot’s id="ID176db9ab-e313-4d76-a60c-bc2a280e9825">',
serverUrl : "https://apis.skype.com",
requestTimeout : 15000,
appId: process.env.APP_ID,
appSecret: process.env.APP_SECRET
}
});
botService.on('contactAdded', (bot, data) => {
console.log('contact added');
bot.reply('Hello ${data.fromDisplayName}!', true);
});
botService.on('personalMessage', (bot, data) => {
console.log('message incoming');
console.log(data);
bot.reply('Hey ${data.from}. Thank you for your message: "${data.content}".', true);
});
const server = restify.createServer();
server.post('/v1/chat', skype.messagingHandler(botService));
const port = process.env.PORT || 8080;
server.listen(port);
console.log('Listening for incoming requests on port ' + port);
Final Edit & Solution: I think the problem caused by Heroku somehow(it could be something with their free tier ,1 dyno). After some effort, I uploaded the program to Azure, and it is now working perfectly.
Potential Solution: You need to change the server address in the server.post command. If you run your program in "https:\www.yourwebsite.com/v1/chat" , you need to modify this;
server.post('/v1/chat', skype.messagingHandler(botService));
to this;
server.post('https:\\www.yourwebsite.com/v1/chat', skype.messagingHandler(botService));
Of course, don't forget to specify your app id, bot id, and app secret. If you don't have one, you need to generate a password in your Skype application page.
I have the exact problem with the OP. I followed the tutorial, and it doesn't specify how to modify our code to comply with our server. So, after running the program it only returns this;
{"code":"ResourceNotFound","message":"/ does not exist"}
In the Echo example in the Skype Bot Webpage; it says;
"We'll assume the bot's URL for messaging was set to https://echobot.azurewebsites.net/v1/chat during registration."
Make sure that Procfile and worker processes are setup.
My bot is working fine on heroku itself

Where do I put database connection information in a Node.js app?

Node.js is my first backend language and I am at the point where I am asking myself "where do I put the database connection information?".
There is a lot of good information regarding this issue. Unfortunately for me all the examples are in PHP. I get the ideas but I am not confident enough to replicate it in Node.js.
In PHP you would put the information in a config file outside the web root, and include it when you need database data.
How would you do this in Node.js? using the Express.js framework.
So far I have this:
var express = require('express'), app = express();
var mysql = require('mysql');
app.get('/', function(req,res) {
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'store'
});
var query = connection.query('SELECT * from customers where email = "deelo42#gmail.com"');
query.on('error', function(err) {
throw err;
});
query.on('fields', function(fields) {
console.log('this is fields');
});
query.on('result', function(row) {
var first = row.first_name;
var last = row.last_name;
res.render('index.jade', {
title: "My first name is " + first,
category: "My last name is " + last
});
});
});
app.listen(80, function() {
console.log('we are logged in');
});
As you can see I have a basic express application with 1 GET route. This route sets off the function to go to the database and pull out information based on an email address.
At the top of the GET route is the database connection information. Where do I put that? How do I call it? How do I keep it out of web root, and include it like PHP ? Can you please show me in a working example. Thanks!
I use the Express Middleware concept for same and that gives me nice flexibility to manage files.
I am writing a detailed answer, which includes how i am use the config params in app.js to connect to DB.
So my app structure looks something this:
How i connect to DB? (I am using MongoDB, mongoose is ORM, npm install mongoose)
var config = require('./config/config');
var mongoose = require("mongoose");
var connect = function(){
var options = {
server: {
socketOptions:{
keepAlive : 1
}
}
};
mongoose.connect(config.db,options);
};
connect();
under the config folder i also have 'env' folder, which stores the environment related configurations in separate files such as development.js, test.js, production.js
Now as the name suggests, development.js stores the configuration params related to my development environment and same applies to the case of test and production. Now if you wish you can have some more configuration setting such as 'staging' etc.
project-name/config/config.js
var path = require("path");
var extend = require("util")._extend;
var development = require("./env/development");
var test = require("./env/test");
var production = require("./env/production");
var defaults = {
root: path.normalize(__dirname + '/..')
};
module.exports = {
development: extend(development,defaults),
test: extend(test,defaults),
production: extend(production,defaults)
}[process.env.NODE_ENV || "development"]
project-name/config/env/test.js
module.exports = {
db: 'mongodb://localhost/mongoExpress_test'
};
Now you can make it even more descriptive by breaking the URL's into, username, password, port, database, hostname.
For For more details have a look at my repo, where you can find this implementation, in fact now in all of my projects i use the same configuration.
If you are more interested then have a look at Mean.js and Mean.io, they have some better ways to manage all such things. If you are beginner i would recommend to keep it simple and get things going, once you are comfortable, you can perform magic on your own. Cheers
I recommend the 12-factor app style http://12factor.net which keeps all of this in env vars. You never should have this kind of information hard-coded or in the app source-code / repo, so you can reuse it in different environments or even share it publicly without breaking security.
However, since there are lots of environment vars, I tend to keep them together in a single env.js like the previous responder wrote - although it is not in the source code repo - and then source it with https://www.npmjs.org/package/dotenv
An alternative is to do it manually and keep it in, e.g. ./env/dev.json and just require() the file.
Any of these works, the important point is to keep all configuration information separate from code.
I agree with the commenter, put it in a config file. There is no ultimate way, but nconf is also one of my favourites.
The important best practise is that you keep the config separate if you have a semi-public project, so your config file will not overwrite other developers.
config-sample.json (has to be renamed and is tracked with for example git)
config.json (not tracked / ignored by git)

Resources