What native javascript method is capable of creating a server? - javascript

I am new to nodejs. I have successfully installed it on my computer (and rebooted). I have created a hello_world.js inside My Documents directory (I'm on a windows xp computer):
console.log("hello world");
var my_http = require( 'http' );
var my_server = my_http.createServer( ... ) ;
...
I have successfully opened a windows command prompt, cd'd to the My Documents directory, executed the .js file, and received 'hello world' output. And I have navigated my browser to the running localhost port (for my experiment: http://localhost:1337/)
But I have 2 major questions based on this:
1 - where is 'http' ... I suppose it is a module(?), but I do not find such a directory within my nodejs installation directory.
2 - how does the http method, createServer, actually create a server? Does native javascript have such a method?

The node.js standard library is written in Javascript and C++, and C++ modules can be loaded in js code via process.binding. Specifically for http.createServer, it's a wrapper around _http_server.Server, which invokes net.Server, which uses the C++ TCP wrapper .
See here for more details.
To answer the second question, createServer just creates and populates the control object, the actual work is in listen, which first creates a handle and this is where C++ code is actually called for the first time.

1) http is a built-in node module. You can read up on the documentation for it here: https://nodejs.org/api/http.html. Node provides a lot of modules out of the box to assist w/ everyday operations (interacting w/ file systems, making HTTP requests, creating servers, working with paths, etc.)
2) Not sure what you mean by "native" JavaScript. JavaScript is just a language. I think you're really asking about the runtime environment. If you are using JavaScript in the browser, then no you can't start an HTTP server. But Node.js runs on the server, so in this environment it can do all sorts of stuff that you can't do w/ JavaScript in the browser, such as access the file system.

Related

Open sessionURL for Autobahn websocket in browser

I have a Pyramid web application on which I would like to embed an iFrame displaying an instance of ParaViewWeb's visualizer so users can display VTU files remotely.
I have successfully done so while running the application on my own workstation by calling a subprocess from Python that executes ParaViewWeb's Quick Start method and returns the URL to JavaScript for iFrame generation.
http://www.paraview.org/ParaView3/Doc/Nightly/www/js-doc/index.html#!/guide/quick_start
However, in order to accommodate multiple users, ParaViewWeb's documentation indicates that
the server must provide a single entry point to establish a connection, as well as a mechanism to start a new visualization session on demand
for which it suggests using Apache as the front-end application and a python launcher to start the process for each session.
Conveniently, I have a "freshly installed Ubuntu Desktop 14.04 LTS" so I used the following guide to configure both the launcher and Apache:
http://www.paraview.org/ParaView3/Doc/Nightly/www/js-doc/index.html#!/guide/ubuntu_14_04
Ok so I'm pretty sure I am missing something major here, but once the launcher is started with /data/pvw/bin/start.sh... how do I then submit the request with information regarding what app to use (visualizer) and what data directory to load???
Update
I am able to launch a session such that a sessionURL with a unique ID is returned by first running
/data/pvw/bin$ ./start.sh
and then entering the following commands in the python interpreter
>>> import requests
>>> import json
>>> data = {"sessionManagerURL": "http://localhost:8080/paraview", "application": "visualizer"}
>>> data = json.dumps(data)
>>> r = requests.post("http://localhost:8080/paraview",data=data)
>>> r.json()['sessionURL']
u'ws://localhost/proxy?sessionId=e2970d68-42c8-11e5-a755-3c970e8061f9'
So now I have a websocket which should contain an instance of ParaViewWeb that I would like to access from the browser... typing the sessionURL as is into the browser does nothing and replacing 'ws' with 'http' opens a page with the following text:
AutobahnPython 0.6.0
I am not Web server, but a WebSocket endpoint. You can talk to me using the WebSocket protocol.
For more information, please visit my homepage.
I am new to both apache and websockets so I am reading up on the protocol on the homepage, but if someone has a quick answer about how to utilize this websocket to display ParaViewWeb to the user I would be very appreciative!!
Note: Command line argument -dr is unknown so omit it from all of the command line arguments given in the guide's launcher.json
Thanks in advance!

Write a variable to a file in Javascript

This may be a copy.. but I'm not getting the thing I want from the answers I saw..
I just want to save a particular variable into a local file using Javascript. I know how to read a file.
I wrote this code..
<script>
var fs = require('fs');
fs.writeFile('http://localhost/online/hello.txt', 'Hello Node', function (err) {
if (err) throw err;
else
{
console.log('It\'s saved!');
}
});
</script>
What is the error here.. or is there a simple and straight-forward way of doing it..??
It seems you're trying to call node-js code from the browser. Although javascript can run in both the browser and on the server (node-js), those are separate systems.
Another thing you can do is google "HTML save file example" and see how this is typically implemented - by opening a save dialog for the user, getting his/her permission, etc. (otherwise any website could just write any file to your computer...).
You are writing NodeJS code for client side application. You must understand the difference between javascript on browser and javascript on NodeJS platform.
Javascript is a language just like C, Java and Python
V8 is a javascript engine to run the javascript application. It is something similar to JRE for Java.
Browser(Only Chrome) uses V8 engine for running javascript application. Other browsers use different javascript engine. Five years ago, there was only one possibility that javascript can only work on browser. You cannot use javascript for application programming like C and Java
NodeJS is a platform which uses V8 to enables developer to write javascript application just like C, Java program. NodeJS also has some inbuilt library for accessing file system,
networks, and much more utilities. One of the internal library in NodeJS is fs. It only works on NodeJS application, not on browser application.
This can be done pretty simply using jrpc-oo. jrpc-oo links the browser and nodejs using the JRPC2 protocol. jrpc-oo abstracts classes over JRPC so that either side (nodejs or the browser) can call eachother.
I have setup an example repo to do exactly this here. Use the writeToFile baranch. I will break out the important parts here.
First in nodejs, we write a class with a method to write input arguments to file. The method looks like so (from the file TestClass.js) :
const fs = require('fs');
class TestClass {
writeToFile(arg){
fs.writeFileSync('/tmp/browser.json',JSON.stringify(arg));
}
}
In the browser we inherit from the jrpc-oo class JRPCClient and call the server class TestClass and method writeToFile like so (from the file src/LitJRPC.js) :
import {JRPCClient} from '#flatmax/jrpc-oo/jrpc-client.js';
export class LitJRPC extends JRPCClient {
writeObjToFile(){
// create the argument we want to save to file
let dat={name:'var',value:10};
// Ask the server to execute TestClass.writeToFile with args dat
this.server['TestClass.writeToFile'](dat);
}
}
Finally we run the nodejs app and the web-dev-server and we look at the browser console and nodejs console to see what happened. You will see the browser variable dat saved to the file /tmp/browser.json
As we are using a secure websocket for jrpc, you will need to generate the certificate and clear the certificate with the browser before the app will work. If you don't want to worry about security then don't use secure websockets. Read the readme in the reference repo for more information on setup and usage.

How run a windows console for JavaScript

I would like to have a console window (a command line) on Windows 7 which will allow me to play with JavaScript just like a python console.
Update:
It's important to have a file access from within the console (or script run through it).
You can use Node.js's REPL. To do so follow this steps:
Download and Install Node.js.
Call Node.js from the Start Menu / Start Screen or directly node.exe installation path (e.g C:\Program Files\nodejs\node.exe).
Enjoy!
You may want to add the installation path to your PATH enviroment variable for ease of use.
Note: to leave node.js press Ctrl + C twice.
To access the local files, you will need the File System module. This is an example of usage:
var fs = require("fs");
fs.readFile(
"C:\\test.txt",
function(err, data)
{
if (!err)
console.log(data.toString());
}
);
This will output the contents of the file C:\test.txt to the console.
Note: An unhandled exception will cause node.js to "crash".
You can just use the developer tools.
For example, in Chrome, press F12. This will bring up the developer tools. The last option on the menubar is console. This will allow you to create JS variables and functions and to interact with DOM elements on the current page
It's possible thanks to Mozilla Rhino JavaScript Engine.
To create a console window for JS:
1) Download Mozilla Rhino JavaScript Engine binary.
2) Extract: js.jar.
3) Create a script to run the console window (e.g. rihno_console.bat):
java -cp js.jar org.mozilla.javascript.tools.shell.Main
For more information about usage (for instance, and global functions inside this console) visit the Rhino Shell web page.
Just like I informed another user with the same question as yours who was faced with the same need, check out DeskJS (https://deskjs.wordpress.com). It's a portable Windows console application that lets you run pure JavaScript code and even load any existing JS files. It supports even the basic JS popup boxes implemented in browsers. You can save your commands as JS files that can be run on startup or by dragging-and-dropping them on the app. Plus there's so much more to it like you can create a build system for Sublime Text that can run JS files via cmd, it supports themes for customizing the entire console and snippets which let you save short snippets of JavaScript code for later use. Improvements are still being made on the app together with other native APIs being included. Hope this helps you as it did for me.

run exe file in local machine using chromium

I need to run an exe file from a html file wrapped into chromium.
I used http://crportable.sourceforge.net to wrap the application into Chromium.
The following code is not working, nothing is actually happening:
function runFile() {
alert('opening file');
w = new ActiveXObject("WScript.Shell");
w.run('C:/Windows/notepad.exe');
return true;
}
before going ahead and tell me that this is a breach of security or that I am an hacker let me explain what I am trying to do. My application run locally (wrapped into chromium) and it need to run an exe file created in Delphi that process a local power point presentation.
I am trying to run notepad.exe just to prove I can run a local file.
Can you help?
Thank you very much
What you're trying to do is not allowed by default. But you can write a C++ method which is available in your Javascript. This C++ method can actually run your application.

How can I edit on my server files without restarting nodejs when i want to see the changes?

I'm trying to setup my own nodejs server, but I'm having a problem. I can't figure out how to see changes to my application without restarting it. Is there a way to edit the application and see changes live with node.js?
Nodules is a module loader for Node that handles auto-reloading of modules without restarting the server (since that is what you were asking about):
http://github.com/kriszyp/nodules
Nodules does intelligent dependency tracking so the appropriate module factories are re-executed to preserve correct references when modules are reloaded without requiring a full restart.
Check out Node-Supervisor. You can give it a collection of files to watch for changes, and it restarts your server if any of them change. It also restarts it if it crashes for some other reason.
"Hot-swapping" code is not enabled in NodeJS because it is so easy to accidentally end up with memory leaks or multiple copies of objects that aren't being garbage collected. Node is about making your programs accidentally fast, not accidentally leaky.
EDIT, 7 years after the fact: Disclaimer, I wrote node-supervisor, but had handed the project off to another maintainer before writing this answer.
if you would like to reload a module without restarting the node process, you can do this by the help of the watchFile function in fs module and cache clearing feature of require:
Lets say you loaded a module with a simple require:
var my_module = require('./my_module');
In order to watch that file and reload when updated add the following to a convenient place in your code.
fs.watchFile(require.resolve('./my_module'), function () {
console.log("Module changed, reloading...");
delete require.cache[require.resolve('./my_module')]
my_module = require('./my_module');
});
If your module is required in multiple files this operation will not affect other assignments, so keeping module in a global variable and using it where it is needed from global rather than requiring several times is an option. So the code above will be like this:
global.my_module = require ('./my_module');
//..
fs.watchFile(require.resolve('./my_module'), function () {
console.log("Module changed, reloading...");
delete require.cache[require.resolve('./my_module')]
global.my_module = require('./my_module');
});
Use this:
https://github.com/remy/nodemon
Just run your app like this: nodemon yourApp.js
There should be some emphasis on what's happening, instead of just shotgunning modules at the OP. Also, we don't know that the files he is editing are all JS modules or that they are all using the "require" call. Take the following scenarios with a grain of salt, they are only meant to describe what is happening so you know how to work with it.
Your code has already been loaded and the server is running with it
SOLUTION You need to have a way to tell the server what code has changed so that it can reload it. You could have an endpoint set up to receive a signal, a command on the command line or a request through tcp/http that will tell it what file changed and the endpoint will reload it.
//using Express
var fs = require('fs');
app.get('reload/:file', function (req, res) {
fs.readfile(req.params.file, function (err, buffer) {
//do stuff...
});
});
Your code may have "require" calls in it which loads and caches modules
SOLUTION since these modules are cached by require, following the previous solution, you would need a line in your endpoint to delete that reference
var moduleName = req.params.file;
delete require.cache[moduleName];
require('./' + moduleName);
There's a lot of caveats to get into behind all of this, but hopefully you have a better idea of what's happening and why.
What's “Live Coding”?
In essence, it's a way to alter the program while it runs, without
restarting it. The goal, however, is to end up with a program that
works properly when we (re)start it. To be useful, it helps to have an
editor that can be customized to send code to the server.
Take a look: http://lisperator.net/blog/livenode-live-code-your-nodejs-application/
You can also use the tool PM2. Which is a advanced production process tool for node js.
http://pm2.keymetrics.io/
I think node-inspector is your best bet.
Similar to how you can Live Edit Client side JS code in Chrome Dev tools, this utilizes the Chrome (Blink) Dev Tools Interface to provide live code editing.
https://github.com/node-inspector/node-inspector/wiki/LiveEdit
A simple direct solution with reference to all answers available here:
Node documentation says that fs.watch is more efficient than fs.watchFile & it can watch an entire folder.
(I just started using this, so not really sure whether there are any drawbacks)
fs.watch("lib", (event_type, file_name) => {
console.log("Deleting Require cache for " + file_name);
delete require.cache[ require.resolve("./lib/" + file_name)];
});

Categories

Resources