File path in Meteor - javascript

I'm having trouble identifying the path to a file in the public directory c:\TEMP\todos\.meteor\local\build\programs\server\public\main.py. Meteor complains the file or directory doesn't exist. Already searched the other postings about the similar issue (e.g., Reading files from a directory inside a meteor app) but didn't help.
Here is the error message.
=> Your application has errors. Waiting for file change.
=> Modified -- restarting.
=> Meteor server restarted
W20151206-04:05:57.893(-5)? (STDERR) Error inside the Async.runSync: ENOENT, no such file or directory 'c:\TEMP\todos\.meteor\local\build\programs\server\public'
Client code
Meteor.call('runPython', function(err, response) {
if(err){
} else {
console.log(response);
}
})
Server code
Meteor.startup( function (){
Meteor.methods({
runPython: function (){
var PythonShell = Meteor.npmRequire('python-shell');
var fs = Meteor.npmRequire('fs');
var runPython = Async.runSync(function (done){
var files = fs.readdirSync('./public/');
// PythonShell.run('main.py', function ... was tried first but Meteor complained that "main.py doesn't exist". So below is a different attempt.
var py = _(files).reject(function(fileName){
return fileName.indexOf('.py') <0;
})
PythonShell.run(py, function (err) {
// PythonShell.run(path.join(py,"main.py") ... was also tried but resulted in the same error
if (err) throw err;
console.log('script running failed');
});
})
return "Success";
}
})
})

All files inside the public folder should be read using '/':
var files = fs.readdirSync('/');
More here: http://docs.meteor.com/#/full/structuringyourapp
For server-side only (might be your case and probably a better solution) you can put everything under the private/ folder and access them by using the Assets API: http://docs.meteor.com/#/full/assets_getText

Clearly I was overthinking it. Specifying a full path to the file was all I needed to do.
PythonShell.run('c:\\project\\public\\main.py', function ...

If your application allows moving the Python script to /private instead of /public, you can take advantage of Meteor's Assets:
Assets allows server code in a Meteor application to access static server assets, which are located in the private subdirectory of an application’s tree. Assets are not processed as source files and are copied directly into your application’s bundle.
e.g. If you move your script to /private/scripts/script.py you can generate the absolute path the Meteor way by doing Assets.absoluteFilePath('scripts/script.py').

Related

Error when importing .js file in one folder to spec.js file in another folder

I am new to the protractor, and trying to create a project in cucumber using POM. Following is the structure of the project:
In the addCustomerPage.js, I have mentioned the locators as well as the functions to perform a test:
var addCustomerPage = function () {
var BankManagerButton = element(by.buttonText('Bank Manager Login'));
***Other locators*****
this.create = async function(fName,lName,pCode){
await BankManagerButton.click();
****rest of the steps*****
}
}
module.exports = new addCustomerPage();
But when in the spec.js, import the above class, on running the code, it throws the error:
E/launcher - Error: Error: Cannot find module '../pages/addCustomerPage'
Following is the spec.js file's code:
var {
setDefaultTimeout
} = require('cucumber');
const {
expect
} = require('chai');
setDefaultTimeout(10 * 1000);
var addCustomerPage = require('../pages/addCustomerPage');
Given('I open the application and click on create customer button', async function () {
**code*****
});
When('I enter {string}, {string}, {string}', async function (fname, lname, pcode) {
return await addCustomerPage.create(fname, lname, pcode);
});
However, this works fine if the pages folder is under the features folder. Can anyone help on what am I doing wrong here?
../
The symbol above is signalling to go up one file directory.
When the variable is declared like this...
var addCustomerPage = require('../pages/addCustomerPage');
... your computer will go up one folder level from the current directory and search for the pages folder and not find it.
When you copied the pages folder and put it under the feature folder, it can detect it because it falls under the directory that you were searching it for
The solution is to:
Just paste your pages folder under features
or
Modify the file path in the variable to where your pages folder is located
Im guessing you have to go up a directory or two, so use this command ../ to get to where your page folder is
var addCustomerPage = require('../../pages/addCustomerPage');
The idea is to modify the file path to wherever the page folder might be

Using RequireJS with node to optimize creating single output file does not include all the required files

I use the FayeJS and the latest version has been modified to use RequireJS, so there is no longer a single file to link into the browser. Instead the structure is as follows:
/adapters
/engines
/mixins
/protocol
/transport
/util
faye_browser.js
I am using the following nodejs build script to try and end up with all the above minified into a single file:
var fs = require('fs-extra'),
requirejs = require('requirejs');
var config = {
baseUrl: 'htdocs/js/dev/faye/'
,name: 'faye_browser'
, out: 'htdocs/js/dev/faye/dist/faye.min.js'
, paths: {
dist: "empty:"
}
,findNestedDependencies: true
};
requirejs.optimize(config, function (buildResponse) {
//buildResponse is just a text output of the modules
//included. Load the built file for the contents.
//Use config.out to get the optimized file contents.
var contents = fs.readFileSync(config.out, 'utf8');
}, function (err) {
//optimization err callback
console.log(err);
});
The content of faye_browser.js is:
'use strict';
var constants = require('./util/constants'),
Logging = require('./mixins/logging');
var Faye = {
VERSION: constants.VERSION,
Client: require('./protocol/client'),
Scheduler: require('./protocol/scheduler')
};
Logging.wrapper = Faye;
module.exports = Faye;
As I under stand it the optimizer should pull in the required files, and then if those files have required files, it should pull in those etc..., and and output a single minified faye.min.js that contains the whole lot, refactored so no additional serverside calls are necessary.
What happens is faye.min.js gets created, but it only contains the content of faye_browser.js, none of the other required files are included.
I have searched all over the web, and looked at a heap of different examples and none of them work for me.
What am I doing wrong here?
For anyone else trying to do this, I mist that on the download page it says:
The Node.js version is available through npm. This package contains a
copy of the browser client, which is served up by the Faye server when
running.
So to get it you have to pull down the code via NPM and then go into the NPM install dir and it is in the "client" dir...

Nodejs Browserify Uncaught TypeError: exists is not a function

I am new to Browserify and trying the following:
I created a node server and trying to get a package called 'openbci' running on the browser.
so I have the following file structure:
Myapp
-...
-public
--app.js
--index.html
--openBCI.js
--...
--javascript
---openBCI
----bundle.js
---...
-node_modules
--openbci
---openBCIBoard.js
--browserify
--...
my app.js file sets the server to serve the public folder
// app.js
var express = require('express');
var app = express();
app.use(express.static('public'));
app.listen(myPort);
then I created the following openBCI.js
// openBCI.js
var OpenBCIBoard = require('openbci').OpenBCIBoard;
exports.OpenBCIBoard = OpenBCIBoard;
and finally launched the browserify command:
$ browserify public/openBCI.js > public/javascript/openBCI/bundle.js
but once called in my index.html file, I got an Uncaught TypeError: exists is not a function at Function.getRoot:
exports.getRoot = function getRoot (file) {
var dir = dirname(file)
, prev
while (true) {
if (dir === '.') {
// Avoids an infinite loop in rare cases, like the REPL
dir = process.cwd()
}
**if (exists(join(dir, 'package.json')) || exists(join(dir, 'node_modules'))) {**
// Found the 'package.json' file or 'node_modules' dir; we're done
return dir
}
if (prev === dir) {
// Got to the top
throw new Error('Could not find module root given file: "' + file
+ '". Do you have a `package.json` file? ')
}
// Try the parent dir next
prev = dir
dir = join(dir, '..')
}
}
It appears that it could not find the original path for the module.
Could you please tell me what is to change? Or if I understood at all how browserify works ? :)
I notice a few things that seem strange about the code.
exists is undefined in JavaScript or node. It appears to be an alias of fs.exists - is that right?
If so, fs.exists is deprecated. Per the documentation, you can achieve the same effect with fs.stat or fs.access. Note however that you should either supply a callback (preferable) or use the Sync version of these methods.
If you are trying to use file system tools in the browser you are going to run into problems because you are attempting to access the server's file system from the browser. There is a plugin, browserify-fs, that gives you an equivalent to fs in the browser. However, this seems to access the browser's local IndexedDB, not the storage on your server.
I would suggest running code that relies on server-side files on the server, rather than in the browser.

Searching files in dir with Node.js

I'm currently trying to search for a few files in a specific folder on Windows using node and grunt.
I have a grunt task that has a function to read a dir with JSON files, but the problem is that when I run the task, the code to read the file doesn't do anything, everything else on that grunt task runs perfect, but that. I'm not sure if the reference for the path is correct, but I'm also using path.normalize() and it does not throws any error.
This is snippet of the code:
..// Some other code
var fs = require('fs'),
path = require("path");
grunt.registerTask('separate', function() {
var filePath = path.normalize("C:\Users\jbernhardt\Desktop\testkeeper\jenkinsReports");
fs.readdir(filePath, function(err, filenames) {
//This log doesn't show as it the function is not running
grunt.log.writeln("Testing");
if (err) {
grunt.log.writeln("Error");
return;
}
filenames.forEach(function(filename){
grunt.log.writeln("Testing");
});
});
...//Some more code below for the same task
}
Does anyone has an idea why this snippet of the code is being skipped when I run the task? I could probably be missing some basic stuffs. Thanks!
Try readdirSync and check if your function still not working. I guess your process is finished before the callback.
You can simply use the __dirname object to get the path where the current script is running:
..// Some other code
var fs = require('fs'),
path = require("path");
grunt.registerTask('separate', function() {
fs.readdir(__dirname, function(err, filenames) {
//This log doesn't show as it the function is not running
grunt.log.writeln("Testing");
if (err) {
grunt.log.writeln("Error");
return;
}
filenames.forEach(function(filename){
grunt.log.writeln("Testing");
});
});
...//Some more code below for the same task
}
You can find more info here.
you need change your path
var filePath = path.normalize("C:\\Users\\jbernhardt\\Desktop\\testkeeper\\jenkinsReports");
Also To achieve consistent results when working with Windows file paths on any operating system, use path.win32:
path.win32.basename('C:\\Users\\jbernhardt\\Desktop\\testkeeper\\jenkinsReports"');
You can read about https://nodejs.org/api/path.html#path_windows_vs_posix
The slash in path are being escaped.
"C:\\Users\\jbernhardt\\Desktop\\testkeeper\\jenkinsReports"
should solve your issue.

How do I use javascript to get a list of files from my server's '/public/Docs' in my Node.js solution?

On Windows 7. In a proprietary app that contains chromium browser. Running on Node.js and Express. In my file 'javascripts/getMyFiles.js' I'm trying to use the following code from: http://nodeexamples.com/2012/09/28/getting-a-directory-listing-using-the-fs-module-in-node-js/
#!/usr/bin/env node
var fs = require("fs"),
path = require("path");
var p = "../"
fs.readdir(p, function (err, files) {
if (err) {
throw err;
}
files.map(function (file) {
return path.join(p, file);
}).filter(function (file) {
return fs.statSync(file).isFile();
}).forEach(function (file) {
console.log("%s (%s)", file, path.extname(file));
});
});
I have 3 problems with this code:
I get and 'Unexpected token ILLEGAL' error from the '#!/use/bin/end node' line
After deleting that first line of code I get the error 'Uncaught ReferenceError: require is not defined'. If I move the '...require...' lines to my root app.js file then the object fs is undefined in my getMyFiles.js file.
I need to specify which folder to list when my app gets an event
I get that require is not available on the client-side, but I don't want to get a list of files from the client side. The files I want to list are in the same path as all of my other files, '/public/Docs'. I can load a known file straight away, but I need to present the user with a list of available documents first. Any assistance will be most appreciated.

Categories