Create a serverside file in Meteor - javascript

I was wondering how to write files in Meteor to the server. I was looking at this NodeJS code, but it wasn't working when I tried it in the server javascript code.
var fs = require('fs');
fs.writeFile("/client/test", "Hey there!", function(err) {
if(err)
console.log(err);
else
console.log("The file was saved!");
});
It was saying that require wasn't defined. Anyways, does anybody know how to write files to the server in Meteor?

You need to use Npm.require instead of just require.
var fs = Npm.require('fs');
This will work for any module that is part of node or meteor (such as fs so its not a problem here). However, for other npm modules you would have to use Meteor NPM or write your own smart package

Related

Using MySQL with Javascript (node.js)

I've just started learning Node.js. I come from a PHP background, so I started with MySQL.
So, I wanted to try executing some basic MySQL queries using javaScript.I write the queries, this way:
filename: test.js
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "test",
});
con.connect(err => {
if (err) throw err;
console.log("Connected!");
const q = "INSERT INTO testing VALUES(3, 'MILLENNIAL', 19, 'STUDENT', 'CSE')";
con.query(q, (err, result) => {
if (err) throw err;
console.log("done");
});
});
When I run the only the javascript file this way: node test.js the query gets executed but when I connect the same file to a html file, this way:
<script src="test.js"></script>
the query doesn't get executed... It gives an error in console: Uncaught ReferenceError: require is not defined
I have feeling that I am not using something very important here. Am I missing something?? Please help me go further.
I am so sorry if this is very silly but, please help me with this. Thank you in advance.
node.js is javascript runtime which uses javascript syntax, which is meant for server-side language. What you trying is to use nodejs script in frontend. require is not defined - because its applicable only for node, to use other modules in plain javascript you will need to use cdn or packages like browserify, webpack. Checkout docs if you are interested.
I will try to explain from a PHP perspective.
When you write PHP, usually your resulting file is an HTML and you embed your PHP code in it, so it renders out without PHP to the requesting browser.
In node, this is different. We don't write the HTML with node code embedded. Node focuses more on backend and frontend separation. You write your backend to reply to your front end.
The backend is where you type var mysql = require('mysql');
You can use something like express vs koa to serve the resulting query to the front end.
Here's a good tutorial to start https://geshan.com.np/blog/2020/11/nodejs-mysql-tutorial/
I usually recommend Koa because it's up updated more regularly now, but express is basically the same thing!
Hope this directs you in the right direction.

Executing python command line tools from NodeJS

What would be the best way to execute command line tools from nodejs to python? I'm working on a app that can generate blockchain certificates.
https://github.com/blockchain-certificates/cert-tools
This is a python based command line tool, where you can generate blockchain certificates. I have followed the steps and everything is working fine in the virtual env. But now I want to know how to implement this in to a app, where I can run the command line tools external from NodeJS. Is this possible? I have found some libraries where you can run python script from nodejs. Example I have used python shell. Whenever I run the setup script, I get missing file errors.
Can someone guide me what the best way will be to solve this problem. Thanks in advance.
You can use python shell in node, you would go about using it somewhat like the following:
var PythonShell = require('python-shell');
PythonShell.run('my_script.py', function (err) {
if (err) throw err;
console.log('finished');
});
for more documentation visit their github repository, hope i could help :)
You should just be able to execute the commands using the child_process.exec() function.
Make sure to only use the file once the python script has finished.
child_process.exec('py path/to/script.py arg1 arg2', (err, stdout, stderr) => {
if (err) {
console.error(err);
return;
}
console.log(stdout);
// check if generated file exists
let fileExists = require("fs").existsSync("/path/to/generated/file");
if (fileExists) {
// do something with the file
}
});

nodejs print file with child-process

I'm learning nodejs and I want to send some file to the printing queue.
I tried elctron-printer and node-printer modules but actually they do not work proprly (can't detect printer with printer.list command for example). Now I'm trying to make it with child_process module and I want to know is there any posibility to start file with its associated application with "print" argument like a python can do it?
For example, this is a code sample of file execution with nodejs:
var childProcess = require('child_process');
childProcess.exec('start printme.txt', function (err, stdout, stderr) {
if (err) {
console.error(err);
return;
}
console.log(stdout);
process.exit(0);// exit process once it is opened
})
Unfortunately it seems that "print" argument is invalid for this code.
And this is a code sample for python and it works fine on windows:
import os
os.startfile('printme.txt', 'print')
All in all I hope that there is possibility to emulate system commands with nodejs.
Otherwise I will have to execute python script via nodejs just for file printing, something like this:
let python = spawn('python', [path.join(app.getAppPath(), '..', 'python_scripts/print_file.py'])
But it is terrible way to do it.

read / write file of remote system in javascript

I got a task to make a button on web page and by clicking on that button I have to read and write a file of local system. How it can be possible.?
Can it be done in node.js or can it be possible if i make any browser app.
Kindly help.
You can read or write files using Nodejs using fs module.
To write file in Node js:
var fs = require('fs');
fs.writeFile(filename, data, [encoding], [callback])
To Read file in Node js :
var fs = require('fs');
fs.readFile(file, [encoding], [callback]);
Your browser doesn't have permission to edit files, you can run a javascript in node.js to read and write files.
var fs = require('fs');
var file = fs.readFile('package.json','utf-8');
console.log(file);

How to localhost a webapp with nodejs

I'm working through designing my first webapp, I've already written a significant portion of the frontend and now I want to make a very simple backend to begin implementing some of the functionality. I've spent the last few days learning as much as I can about effective backend development and other various things, but I've run into a huge problem. I fundamentally don't understand how to attach my front end and my backend (which I want to use nodejs for).
All I want is to use my browser to go to localhost:8080 and automatically see the html document with my frontend then within my frontend code have the app communicate with the server (to get json info or instruct the server to add things to a database or things like that).
Once you have installed node in your system.
Folder structure:
Keep your files in public folder inside app folder
Navigate to your application folder in Terminal or Command Prompt:
Then create a file as package.json and keep following code in it:
{
"name" : "YourAppName",
"version" : "0.0.1",
"description" : "App description",
"dependencies" : {
"mime" : "~1.2.7"
}
}
then come back to terminal and run npm install
Then create a file as server.js and keep following code in it:
var http = require("http");
var fs = require("fs");
var path = require("path");
var mime = require("mime");
var cache = {};
function send404(responce){
responce.writeHead(404,{"content-type":"text/plain"});
responce.write("Error 404: resourse not found");
responce.end()
}
function sendFile(responce,filePath,fileContents){
responce.writeHead(200,{"content-type": mime.lookup(path.basename(filePath))});
responce.end(fileContents);
}
function serveStatic(responce,cache,abspath){
if(cache[abspath]){
sendFile(responce,abspath,cache[abspath]);
}else{
fs.exists(abspath,function(exists){
if(exists){
fs.readFile(abspath,function(err,data){
if(err){
send404(responce);
}else{
cache[abspath] = data;
sendFile(responce,abspath,data);
}
})
}else{
send404(responce)
}
})
}
}
var server = http.createServer(function(request,responce){
var filePath = false;
if(request.url == '/'){
filePath = 'public/index.html';
}else{
filePath = 'public'+request.url;
}
var abspath = './'+filePath;
serveStatic(responce,cache,abspath);
})
server.listen(8080,function(){
console.log("server running on 3000");
})
** This code is to help you get started with node js, for better understanding go to node documentation. Read about the mime module too, it is being used here.
You can use free cloud services such as Parse.com. this js sdk
You can use Grunt and using Connect plugin, create a simple server, sufficient for developing pure JS web applications.
Using Grunt basically requires 2 files
package.json
Gruntfile.js
package.json defines the dependencies required by Grunt to run. In your case it would include
grunt
grunt-contrib-connect (The plugin for setting up a server)`
It may also include additional dependencies based on your requirements.
Gruntfile.js defines the configuration for dependencies. In your case how the server should be setup. If you use plugins other that grunt-contrib-connect you should configure them too.
Reference:
Grunt: The JavaScript Task Runner

Categories