I am making a small project in which I need to start a cluster from the server file and that file I need to get from the commander cli argument.
program.start is to get the file name.
let filePath = fs.readFile(process.cwd() + "\\"+`${program.start}`, function(err, data)
{
if(err)
console.log(err)
else
console.log("completed");
});
if(cluster.isMaster){
const cpus = os.cpus().length;
console.log('Forking for ${cpus} CPUs');
for (let i = 0; i<cpus;i++){
cluster.fork();
}
}
else{
require(filePath);
}
AssertionError [ERR_ASSERTION]: missing path
I am stuck need help in this.
Related
I have the following code that is working now.
I have a script with javascript that use nodejs and read a csv file but I don't know how to use the data from csv in newman.run
var fs = require('fs');
var people = [];
var fileContents = fs.readFileSync('users.csv');
var lines = fileContents.toString().split('\n');
const newman = require('newman'); // require newman in your project
for (var i = 0; i < lines.length; i++) {
people.push(lines[i].toString().split(','));
}
for (var i = 0; i < lines.length; i++) {
console.log(people[i][0]);
newman.run({
collection: require('collection.json'),
environment: require('environment.json'),
reporters: 'htmlextra',
}, function (err) {
if (err) { throw err; }
console.log("i"+'collection run complete!');
});
}
I try to explain what's happening.
I iterate over csv file correctly but I don't know how to pass the values of csv in body about post.
Could aynone help to me?
To use a datafile with Newman, from a script - you would only need to add the iterationData key to the newman.run object and then reference the filename as the value.
const newman = require('newman');
newman.run({
collection: require('collection.json'),
environment: require('environment.json'),
iterationData: '<path to file>/users.csv',
reporters: 'htmlextra',
}, function (err) {
if (err) { throw err; }
console.log('collection run complete!');
});
To use the values in the requests, you would need to add this variable names using the {{var_name}} syntax which would reference the CSV column headings.
More information about working with data files can be found here:
https://learning.getpostman.com/docs/postman/collection-runs/working-with-data-files/
I am building an app with Electron in which there are some executables which run just fine when running npm start from terminal using the child-process in Javascript. However when packaging it with electron-builder my app just cannot find the executables. I have read many related posts and none answer my question.
The solution here https://github.com/sindresorhus/fix-path does not resolve my issue.
Here is my code
function updateCourses(platform){
const fixPath = require('fix-path');
alert(process.env.PATH);
fixPath(); //This is the package but does not resolve my issue
alert(process.env.PATH);
const path=require('path');
var fs = require("fs");
var mysql=require("mysql");
// /Applications/mooc-platform.app/
alert(__dirname);
const { exec } = require('child_process');
var run="./../../Users/thanasis/Desktop/mooc-platform\ Mac/scrape_"+String(platform);
exec(run,(error, stdout, stderr) => {
if (error) {
alert(`exec error: ${error}`);
alert(`Something wrong happened: ${stdout}`);
alert(`stderr: ${stderr}`);
return;
}
else{
alert(platform+" courses downloaded");
alert("Updating database");
var con=mysql.createConnection({
host: "localhost",
user: "root",
password: "simple1234",
database: "moocs"
});
var v=false;
con.connect(function(err){
if(err) throw err;
console.log("Connected!");
platform=String(platform);
var num = fs.readFileSync("../../Users/thanasis/Desktop/mooc-platform\ Mac/courses/"+platform+"/numofcourses.txt");
num=parseInt(num,10);
let plat=platform;
for(i=0; i<num; i++){
pth="../../Users/thanasis/Desktop/mooc-platform\ Mac/courses/"+platform+"/course"+i.toString()+".json";
var content = fs.readFileSync(pth);
var object = JSON.parse(content);
String.prototype.setCharAt = function(index,chr) {
if(index > this.length-1) return str;
return this.substr(0,index) + chr + this.substr(index+1);
}
var ti=String(object.title);
ti=ti.replace(/'/g,'i');
sql="INSERT INTO courses (name) VALUES('"+ti+"') ON DUPLICATE KEY UPDATE hits=0";
con.query(sql,function(err,result){
if(err) throw err;
console.log(result);
});
// con.query('DELETE FROM courses',function(err,result){
// if(err) throw(err);
// console.log(result);
// });
}
v=true;
con.end(function(err,result){
if(err) throw err;
if(!alert("Updated")){
window.location.href="load_courses.html";
}
});
});
}
});
}
Optimally this would run from the applications folder (in Macos) with no issue.
Any help would be greatly appreciated.
Assuming you are packaging your app as asar:
All your paths are relative to your file. So the moment this file changes its location the path won't work anymore.
Packing with asar changes
C:\myApp\scripts\main.js
to
C:\myApp\resources\myAppName.asar\scripts\main.js
so your files cannot be found from there.
There are a couple of options. For example:
Putting all of your executables and text files inside the asar.
Upside: you can distribute them with your app. Downside: App might
get big and this will not work with all executable files, as some may
need dependencies on their own.
Determine somehow an absolute path on the current machine (I have no
idea of macOS. On Windows I read the registry and extract the path I
need from there.)
Provide different paths if packed or not via e.g.
electron-is-running-in-asarpackage.
I'm having issues with a function that reads a text file line by line. It says the file I'm trying to read does not exist, although it does in the file path I am running node on. What could be the issue??
function insertUsers(auth) {
fs.readFile('emails.txt', function (err, data) {
if (err) throw err;
var person = data.toString().split("\n");
var person = data.toString().split("\n");
for (var i = 0; i < person.length(); i++) {
service.members.insert({
groupKey: 'testgroup#x.com',
resource: {
email: person[i],
role: 'MEMBER',
}
}, (err, res) => {
if (err) { return console.error('The API returned an error:', err.message); }
const user = res.data.member;
if (member.length) {
write_log('Inserted' + email + ' into student group.');
} else {
write_log('Failed to delete ' + email);
}
});
}
});
}
https://i.stack.imgur.com/5UTK6.png and https://i.stack.imgur.com/iVvnA.png
Verify that you're starting your node application from the same location where your file (emails.txt) is. According to your method logic it should be
C:\Users\[]\source\repos\StudentGroups\StudentGroups > node main.js
you can check the current working directory from the code
console.log(process.cwd())
it should be
C:\Users\[]\source\repos\StudentGroups\StudentGroups
Otherwise, modify your code to correctly point to the email.txt or start your application from the correct directory.
This problem was due to how I made emails.txt. The name is "emails.txt", and the file extension is .txt. I changed the file name to "emails", and it worked.
There are many ways to write this code but I can't understand why my version is not working.
The program should take 2 arguments from the command line. The first is the path to a folder with files, and the second arg is a file extention. The output should print only the files with the same extention as the second argument.
When I try to execute this code with the 2 arguments i get an empty output.
var fs=require('fs');
var path=require('path');
var filepath=process.argv[2];
var ext="."+process.argv[3];
fs.readdir(filepath,function(err,list) {
if (err) throw err;
for (var i=0;i<list.length-1;i++) {
if (("."+path.extname(list[i]))==ext) {
console.log(list[i]);
}
}
});
Please, delete 'utf-8', you just need type (and read docs http://nodejs.org/api/fs.html#fs_fs_readdir_path_callback):
fs.readdir(filepath,function(err,list){
path.extname() returns an extension with a dot as seen here: link; there's no need for "."+path.extname.
list.length-1 in your for loop doesn't make much sense when you consider how you've initialized your loop. list.length is the correct choice.
For reference on how to solve this problem, please see code below
var fs = require("fs")
var path = require("path")
var pathToUse = process.argv[2]
var ext = "."+process.argv[3]
fs.readdir(pathToUse, function(err, files){
if(err){
throw err;
}
else{
var filteredFiles = files.filter(function(file){
if(path.extname(file) === ext){
return true;
}
else{
return false;
}
});
for(var x = 0; x < filteredFiles.length; x++){
console.log(filteredFiles[x];
}
}
});
I need help in upload multiple files using node.js upload file reader.
I am using the fs = require('fs').
I have problem in choose two files,only one file only write in upload directory.
This is my backend
var files = req.files.files[0];
for (var i = 0; i < files.length; i++) {
file = files[i];
fs.readFile(files[i].path, function(error, data) {
// console.log( files[i].path ) ,here displayed two same both
fs.writeFile(uploadDirectory() + newFileName, data, function(error) {
});
});
}
Please help me.
what is the problem in my code.
Thanks.
You should avoid using files[i] in asynchronous function's callback which is directly written inside of for-loop.
the reason why console.log( files[i].path ) displays same thing twice is because when the code is loaded,the for-loop has already done. so you always get the last element of the array.
the easiest way to fix that is making a new scope(function)
for (var i = 0; i < files.length; i++) {
readAndWriteFile(files[i]);
}
var readAndWriteFile = function(file){
fs.readFile(file.path, function(error, data) {
// console.log( file.path ) displays what you expect.
fs.writeFile(/* define new file name */, data, function(error) {
});
});
}