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.
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 have a frontend which sends the HTML of that page to a Node.js server. The server should then send that HTML to Azure BlobStorage.
Here is my express route to handle this:
router.post("/sendcode", function(req, res) {
let code = "";
code = req.body.code;
console.log(code);
let service = storage.createBlobService(process.env.AccountName, process.env.AccountKey);
service.createContainerIfNotExists("htmlcontainer", function(error, result, response) {
if (error) {
throw error;
} else {
service.createBlockBlobFromStream("htmlcontainer", code, function(err, result, response) {
if (err) {
throw err;
} else {
console.log(result);
console.log(response);
}
});
}
});
});
When I call this route, I receive this in my console:
<html><style>* { box-sizing: border-box; } body {margin: 0;}</style><body></body></html>
How can I send it to BlobStorage? Avoid the method I used as it maybe wrong because I can't figure out what function to use because of scarce documentation.
There are many answers on stack overflow, you can follow this one and adjust it to your needs:
Uploading a file in Azure File Storage using node.js
So after trying a little bit, i was able to send it not from stream but after writing it to a file, sending that file through createBlockBlobFromLocalFile function in azure-storage module and deleting the file from disk.
I know this isnt the most efficient method out there but it got my work done.
The problem i was facing was that after uploading html code in a block blob(without file operation), its content type was application/octet which i wanted to be text/html. So i had to perform one more operation to change its content type, which i found to be a little difficult due to unavailability of documentation and examples in javascript.
I have read all the questions on SO that I could find. They all use Express, Mongoose or they leave something out. I understand that Node.js is the server. I understand the MongoDB require is the driver the Node.js server uses to open a connection to the MongoDB. Then, on the server, I can do (from the documentation):
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var ObjectId = require('mongodb').ObjectID;
var url = 'mongodb://localhost:27017/test';
var findRestaurants = function(db, callback) {
var cursor =db.collection('restaurants').find( );
cursor.each(function(err, doc) {
assert.equal(err, null);
if (doc != null) {
console.dir(doc);
} else {
callback();
}
});
};
// Connect to the db
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
findRestaurants(db, function() { //I don't want to do this as soon as the server starts
db.close();
});
});
//if I put findRestaurant here,
function findRestaurant(data){
}
How do I call it from the client?
I do not want to find data as soon as I start the server. I realize those are examples, but what I cannot find is a way where the client requests some data and where the Node.js server returns it.
I have seen close examples using jQuery, Angular on the client, and then Express, Mongoose, Meteor, , etc.
All I want to understand is how I make this request from the client's browser. I can do that with XMLhttpRequest(), so I can put that part together, I believe. But, any example is appreciated.
But what is waiting on the Node.js side of things (how do I set up my function to be called once the server is listening)?
How do I create a function on the server side, maybe "GetRestaurants" and have that return the data it gets using find()?
I cannot find this information, this simple, anywhere. Is it too complicated to do the example without a framework?
I do not wish to copy and paste from something using Express, etc. without understanding what's going on. Most explanations never say, this goes on the Node.js side. This is client. I know I am expected to do my own research, but I am not putting it together, too used to RDBMSes, IIS, Apache, PHP, and so on.
I believe I have a fundamental misunderstanding of what's going on in the paradigm.
Please. No REST API creation, no frameworks of any kind on Node.js other than using the MongoDB library (unless there is an absolute requirement), not even jQuery, Angular, Jade, or anything else for the client side, straight up JavaScript on all sides.
I have seen questions like this,
How to display data from MongoDB to the frontend via Node.js without using a framework
But they do not show what I am asking. They do it all at once, as soon as the database connects. What if I want to do a delete or insert or find? There are many SO questions like this, but I have not hit the one that shows what I am looking for.
This should give the guidance. Once you go to a browser and type http://localhost:5155 the callback function (request, response) { will be called and the request to db will be made. Make sure you get response and then start working on the client side code:
const http = require('http');
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const url = 'mongodb://localhost:27017/test';
const server = http.createServer(function (request, response) {
getData(function (data) {
response.end(data);
});
});
function getData(callback) {
// Connect to the db
MongoClient.connect(url, function (err, db) {
assert.equal(null, err);
findRestaurants(db, function (data) {
db.close();
callback(data);
});
});
const findRestaurants = function (db, callback) {
const cursor = db.collection('restaurants').find();
const data = [];
cursor.each(function (err, doc) {
assert.equal(err, null);
data.push(doc);
if (doc === null) {
callback(data);
}
});
};
}
server.listen(5155);
I'm creating an app with Electron. I was need to sent file to server with Socket.IO, so I installed socket.io-stream module. I tested on browser, it works well. But do same in Electron, it always fails with
TypeError: Invalid non-string/buffer chunk
This is server side code:
ss(socket).on('/user/update/profile', (stream, data) => {
const filename = path.basename(data.name);
const ws = fs.createWriteStream(`userdata/profile/${filename}`);
stream.on('error', (e) => {
console.log('Error found:');
console.log(e);
});
stream.on('drain', (e) => {
console.log('drain');
});
stream.on('data', () => {
console.log('data');
});
stream.on('close', () => {
console.log('close');
});
stream.pipe(ws);
//ss(socket).emit('/user/update/profile', {});
});
And this is client side code:
var file = ev.target.files[0];
var stream = ss.createStream();
ss(socket).emit('/user/update/profile', stream, {
email: this.props.user.email,
name: file.name,
size: file.size
});
var blobStream = ss.createBlobReadStream(file);
var size = 0;
blobStream.on('data', (chunk) => {
size += chunk.length;
console.log(`${size} / ${file.size}`);
});
blobStream.pipe(stream);
code is quite simple, just from the example in module's introduction page on NPM. I already said that it worked as browser. You see that I logged every file uploading progress on the console. Using Electron, sending file seems to work because it logged every data size, but on server side, it fails.
I found similar issue with NW.js and that guy solved his problem with his own way but that didn't worked for me.
It will be very appreciate help me how should I do.
The error means your are passing a non-string (e.g. an object) where a string is expected. I cannot see where that might be offhand but since it works in the Browser but not Electron it might be that the underlying Javascript engines have a different tolerance for the issue. Can you run the same in a node debugger? Does one of the streams complain or break oddly? Can you narrow down which line this is coming from?
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.