I want from the html component part, call a JavaScript file to run a command, clicking on a button.
But when I click the button nothing happens:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<p id="counter">Loading button click data.</p>
<button id="buttonForScraping">begin to scrape!</button>
<script>
function startScrape(){
jQuery.ajax({
type:'get',
url:'../../../scraping.js',
data:[],
dataType:'json',
success: function(rs)
{},
failure : function(rs)
{}
});
}
</script>
</body>
</html>
This is the html code, and the js file is :
const {exec} = require('child_process');
const button = window.document.getElementById('buttonForScraping');
button.addEventListener('click', function(e) {
exec('scrapy crawl address', (err, stdout, stderr) => {
console.log(`stdout: ${stdout}`);
console.log(`stderr: ${stderr}`);
});});
The scrapy command is a Python command, so I need to make an ajax call to run it on the server, I think.
To run code on the serverside, you actually need a server to answer requests. That could look like this:
const { exec } = require('child_process');
const app = require("express")(); // "npm install express" to install this dependency
app.get("/adress", (req, res) => { // server this path
exec('scrapy crawl address', (err, stdout, stderr) => {
res.json({ // respond to client if the command was done
stdout: "" + stdout,
stderr: "" + stderr
});
});
app.listen(80,() => console.log("server started"));
That will open a server on port 80 if you start the script with node ./scrapping.js, and respond with JSON if you visit it on http://localhost/adress
Now whenever the button gets clicked on the frontend, you have to start an aJAX request to the backend:
// "async" lets us write callbacks more gracefully
button.addEventListener('click', async function(e) {
try {
// fetch is like $.ajax, but its native
// 'await' is like a callback
const { stdout, stderr } = await fetch("http://localhost/adress").then(res => res.json());
console.log(stdout, stderr);
} catch(err) {
console.error("error occured while pinging server", err);
}
});
To execute a JavaScript function when clicking a button, you can use a sample like this.
First, create the HTML button and use the onClick():
<button onClick="doSomething()">Button Text</button>
The onClick() tells the browser to execute a JavaScript function. Now in the JavaScript file put create your function:
function doSomething() {
alert('do something');
console.log('do something ')
}
This simple function outputs to the console log and throws an alert, but functions can get a lot more complex than that.
To execute a server side method or python command from an HTML page, you're going to have to need a more complex architecture probably.
You have to include the js file into the html file like in the example.
Note: Make sure the path of the js file is correct in src attribute of script.
<script src ="myScript.js"></script>
Related
I'm trying to execute this function but in the terminal with Node.JS
var WebTorrent = require('webtorrent')
var client = new WebTorrent()
var magnetURI = 'magnet: ...'
client.add(magnetURI, { path: '/path/to/folder' }, function (torrent) {
torrent.on('done', function () {
console.log('torrent download finished')
})
})
I mean, for example, create an <button> tag, and when is clicked,
that the previous function be executed in the nodejs console, not in the browser console.
EXTRA:
I'm executing this two files:
app.js
let http = require('http');
let fs = require('fs');
let handleRequest = (request, response) => {
response.writeHead(200, {
'Content-Type': 'text/html'
});
fs.readFile('./index.html', null, function (error, data) {
if (error) {
response.writeHead(404);
respone.write('Whoops! File not found!');
} else {
response.write(data);
}
response.end();
});
};
http.createServer(handleRequest).listen(8000);
And
index.html that contains the <button> tag but does nothing.
Client(browser) and server are two different entities, when client is browser the only way to communicate is through HTTP protocol, in simple terms use internet.
Now browser understand only it's own kind of javascript, more precisely ECMA but not nodejs. So the following code could not be executed in browser
var WebTorrent = require('webtorrent')
var client = new WebTorrent()
Hence I would assume it is running on server which your machine and hence console.log will print to your terminal.
To run it on browser, I assume you will have to code it differently, either you will have to use browserify and analyze the client side script OR code only in client side with below libaray :
<script src="webtorrent.min.js"></script>
For more details refer, complete web page example at https://github.com/webtorrent/webtorrent/blob/master/docs/get-started.md
I'm new to node js and i'm trying to do the following:
function createPasswordfile(content)
{
fs.writeFile(passwordFileName,content, function(err) {
if(err) {
console.log("Failed on creating the file " + err)
}
});
fs.chmodSync(passwordFileName, '400');
}
function deletePasswordFile()
{
fs.chmodSync(passwordFileName, '777');
fs.unlink(passwordFileName,function (err) {
if (err) throw err;
console.log('successfully deleted');
});
}
and there are three statements which call these functions:
createPasswordfile(password)
someOtherFunction() //which needs the created password file
deletePasswordFile()
The problem I'm facing is when I add the deletePasswordFile() method call, I get error like this:
Failed on creating the file Error: EACCES, open 'password.txt'
successfully deleted
Since its non blocking, I guess the deletePasswordFile function deletes the file before other function make use of it.
If deletePasswordFile is commented out, things are working fine.
How should I prevent this?
writeFile is asynchronous, so it's possible the file is still being written when you try and delete it.
Try changing to writeFileSync.
fs.writeFileSync(passwordFileName, content);
I am trying to run some command on the client system through server. I know server has lots of security issues while executing server commands, is there any way to run command form browser.
I have following commands in nodejs but, i need this to run form the browser in clients system.
same as in this question but form html page.
node.js shell command execution
function run_cmd(cmd, args, callBack ) {
var spawn = require('child_process').spawn;
var child = spawn(cmd, args);
var resp = "";
child.stdout.on('data', function (buffer) { resp += buffer.toString() });
child.stdout.on('end', function() { callBack (resp) });
}
Usage:
run_cmd( "ls", ["-l"], function(text) { console.log (text) });
No, you may not execute arbitrary shell/console commands through a browser.
The security implications for this would be gigantic. You wouldn't want someone to execute:
run_cmd( "rm", ["-rf *"], function(text) { console.log ("lol") });
Through your browser. Not even if you could explicitly trust it.
I'm having an html file with a hyperlink which calls javascript function.The javascript function has to call a batch file...this all should happen from Node.js
<html>
<head>
<title>sample</title>
<script src="child.js"></script>
</head>
<body>
click here
</body>
</html>
child.js
function call()
{
var spawn = require('child_process').spawn,
ls = spawn('append.bat');
}
I'm getting error like this....
ReferenceError: require is not defined
var spawn = require('child_process').spawn,
any answer..pls reply...
Node.js is a server-side environment for JavaScript. To interact with it from a web page, you'll want to establish an http.Server and use Ajax to communicate between.
A partial example (using a few libraries to simplify) would be:
// server-side
app.post('/append', function (req, res) {
exec('appand.bat', function (err, stdout, stderr) {
if (err || stderr.length) {
res.send(500, arguments);
} else {
res.send(stdout);
}
});
});
// client-side
function call() {
$.post('/append').done(function (ls) {
console.log(ls);
}).fail(function (xhr) {
console.error(xhr.responseText);
});
}
The libraries demonstrated are Express for server-side and jQuery for client-side. It also uses child_process.exec() rather than spawn() to get Buffers rather than Streams.
Resources:
Learn jQuery
Express Guide
SO's node.js Tag Info, which includes a number of "Tutorials, Guides and Books" and "Free Node.js Books and Resources."
You can't access Node.js from browser.
I have the following code and I know that if I use it in the terminal (node test.js, in the case the file is called test.js) but how do I make this code work in javascript with HTML? I mean, how do I make possible to click a button and execute the code? Thank you!
var SerialPort = require("serialport").SerialPort
var serialPort = new SerialPort("/dev/ttyACM0", {
baudrate: 9600
}, false);
serialPort.on('error', function(err) {
console.log(err);
});
serialPort.open(function(err) {
if (err) {
console.log(err);
return;
}
console.log('open');
serialPort.on('data', function(data) {
console.log('data received: ' + data);
});
serialPort.write('1', function(err, results) {});
});
}
You can't execute this in a browser (which wouldn't let you access the serial port, for example) but there are various solutions to package some HTML code with nodejs.
The best solution today for a local all-including "desktop-type" architecture is probably node-webkit which has a good support and traction.
Another standard architecture is to simply make nodejs act as a server serving an HTML page including your button. That might be more suited for piloting an Arduino.