calling child_process from nodejs - javascript

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.

Related

How can I call a JavaScript function through html button?

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>

using api's in node.js

i'm running the server using node.js on localhost:8080 and i want to use api's in my HTML document. the html document is external, so how would i go about sending the api data to the web page. for example, i have a weather api in my javascript file:
var yw = require('weather-yahoo');
var ans = {};
function loadWeather() {
yw.getSimpleWeather('denver,co').then(function(res){
console.log(res);
ans=res;
alert(ans);
}); // pulls just some of the info from yahoo weather
}
and i've called it on button click in my html file like so:
<button onclick="loadWeather();">View article descriptions</button>
but it doesn't work. i also have the included the source of the javascript file in this document by the way.
You have a function on your node server, but now you'll need to expose it to your client. The simplest way to do this is using the express module.
If you are not completely familiar with node modules and express, there are plenty of startup tutorials available such as https://expressjs.com/en/starter/hello-world.html.
In your case you would need to create an API call that will call the weather data function.
var app = require('express')(),
yw = require('weather-yahoo');
function loadWeather() {
return yw.getSimpleWeather('denver,co');
}
app.get('/weather', function(req, res){
loadWeather().then(function(result){
return res.json(result);
},
function(error){
res.status(400).json(error);
});
});
app.get('/', function(req, res){
res.sendFile(process.cwd() + '/index.html', null, function(err) {
if(err){
res.sendStatus(404);
}
});
})
app.listen(3000, function () {
console.log('Listening on port 3000');
})
This is the simplest of API calls that can easily be extended to return weather for other regions by adding query parameters to the api call.
On the client side, you will now need a function to call your api.
As the example above serves the index file as it's main page, a simple JQuery get call to weather will return the data you want as it is on the same host.
<script>
//This call uses JQuery, make sure you have it referenced in your site
function callAPI() {
$.get("weather", function(data, status){
$('#result').val(JSON.stringify(data));
});
}
</script>
<button onclick="callAPI()">Get Weather</button>
<br>
<textarea id="result" style="width:500px; height:500px"></textarea>

Call a function in node.js

I am new to node.js .Here I write a sample function in node.js to print the contents of a json file as follows.
exports.getData =function(callback) {
readJSONFile("Conf.json", function (err, json) {
if(err) { throw err; }
console.log(json);
});
console.log("Server running on the port 9090");
What I am doing here is I just want to read a json file and print the contents in console. But I do not know how to call the getData function. While running this code it only prints the sever running on the port..", not myjson` contents.
I know the above code is not correct
How can I call a function in node.js and print the json contents?
Node.js is just regular javascript. First off, it seems like you are missing a }. Since it makes the question easier to understand, I will assume that your console.log("Server... is outside exports.getData.
You would just call your function like any other:
...
console.log("Server running on the port 9090");
exports.getData();
I would note that you have a callback argument in your getData function but you are not calling it. Perhaps it is meant to be called like so:
exports.getData = function(callback) {
readJSONFile("Conf.json", function (err, json) {
if(err) { throw err; }
callback(json);
});
}
console.log("Server running on the port 9090");
exports.getData(function (json) {
console.log(json);
});
Truthfully, your getData function is a little redundant without any more content to it since it does nothing more than just wrap readJSONFile.
Don't take this the wrong way, but your code appears to be a mixed up mess of unrelated examples. I recommend you start by learning the basics of JavaScript and node.js (for example, read Eloquent JavaScript and Felix's Node.js Beginners Guide).
But on to your code. First of all, you are creating a function (called getData) and exporting it. Then you're printing "Server running on the port 9090". There is no server code in your script, and the function you created is never executed.
I think this is what you intended to write:
readJSONFile("Conf.json", function (err, json) {
if(err) { throw err; }
console.log(json);
});
Assuming that readJSONFile is a real function.

How to make javascript code to work witn node.js?

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.

Access file on a Node.js server

If you are familiar with NowJS, one you start an instance of Now on the server, you can access a file located on the server by <script src="http://localhost:8080/nowjs/now.js"></script>
Any ideas on how to implement this?
Thanks,
Mark
There are many static file handler modules already in node, take a look at:
https://github.com/joyent/node/wiki/modules#wiki-web-frameworks-static
Most popular are:
https://github.com/felixge/node-paperboy
and
https://github.com/cloudhead/node-static
Using node static is as simple as:
var static = require('node-static');
var file = new(static.Server)('./public');
require('http').createServer(function (request, response) {
request.addListener('end', function () {
file.serve(request, response);
});
}).listen(8080);

Categories

Resources