i want to run a script that will create a directory and within a file and subdirectory, something like this
main-folder
> sub-folder
> file
so far i haven't had any luck, my thought is trying to writeFile within the mkDir function
const fileGenerator = (fileName, fileContent) => {
fs.writeFile(fileName, fileContent, (err) => {
if (err) throw err;
console.log('The file has been saved!');
});
}
fs.mkdir('main-folder', err => {
if (err) {
console.log(err);
} else {
fileGenerator('index.html', 'hello');
console.log('Directory Created');
fs.mkdir('sub-folder', err => {
if (err) {
console.log(err);
} else {
console.log('Directory Created');
}
})
}
})
The code is 'working as inteded'. The place where're you creating your subfolder and file is just the callback. The mkdir function from the Node Filesystem still needs the full path. It doesn't know that its under "main-folder".
See the edited code:
const fs = require('fs');
const fileGenerator = (fileName, fileContent) => {
fs.writeFile(fileName, fileContent, (err) => {
if (err) throw err;
console.log('The file has been saved!');
});
}
fs.mkdir('main-folder', err => {
if (err) {
console.log(err);
} else {
fileGenerator('main-folder/index.html', 'hello');
console.log('Directory Created');
fs.mkdir('main-folder/sub-folder', err => {
if (err) {
console.log(err);
} else {
console.log('Directory Created');
}
})
}
})
Your code created the main-folder, sub-folder and index.html, just all relative to js file.
Related
function Getir() {
var options =
{
host: 'example',
port: 443,
path: '/myUrl'
};
get(options, function (http_res) {
var data = "";
http_res.on("data", function (chunk) {
data += chunk;
});
http_res.on("end", function () {
writeFile('NewHtml.txt', `${data}`, 'utf8', (err) => {
if (err) console.log(err);
});
});
});
}
function DegistirDuzenle() {
if (existsSync("./DatabaseHtml.txt")) {
var DataBaseHtml = readFileSync("./DatabaseHtml.txt", 'utf-8', (err) => { if (err) console.log(err) });
var MyHtml = readFileSync("./NewHtml.txt", 'utf-8', (err) => {if (err) console.log(err) });
if (MyHtml == DataBaseHtml) {
unlink("./NewHtml.txt", (err)=>{ if(err) console.log(err)});
console.log("değişiklik yapılmadı");
} else {
//notification
console.log("değişiklik yapıldı");
//Change
unlink('./DatabaseHtml.txt', (err) => { if(err) console.log(err); });
writeFile('./DatabaseHtml.txt', `${MyHtml}`, 'utf-8', (err) => { if(err) console.log(err); });
unlink('./NewHtml.txt', (err) => { if(err) console.log(err); });
}
}
else {
writeFile('DatabaseHtml.txt', `NewDataBaseHtml`, 'utf8', (err) => {
if (err) console.log(err);
});
}
}
async function Mysystem() {
let mypromis = new Promise((resolve, reject)=>{
resolve(Getir());
});
await mypromis.then(DegistirDuzenle());
}
Mysystem();
I want to create a txt file, read it and delete it later. I have 2 function 1.(Getir()) Create txt, 2.(DegistirDuzenle()) read txt and delete but 2. function starts working first and I getting error. "Error: ENOENT: no such file or directory, open './NewHtml.txt'"
async function Mysystem() {
let mypromis = new Promise((resolve, reject)=>{
resolve(Getir());
});
await mypromis()
await DegistirDuzenle()
}
Mysystem()
You should use
async function Mysystem() {
await Getir();
await DegistirDuzenle();
}
or
function Mysystem() {
return Getir().then(DegistirDuzenle);
}
but not a mix of them. Also notice that when passing the DegistirDuzenle function to .then() as a callback, it shouldn't be invoked (passing the result of a call, not passing the function). Alternatively, you could write .then((getirResult) => DegistirDuzenle()).
Also, for this to work, you'll need to properly promisify the code in Getir and DegistirDuzenle.
So I come to this, I want to write into a DB and do other operations to work with my program logic, this is the guide that I'm following Node.js Class Creation:
//## This is my mysql_test.js file
function MySQL(){
var mysql = require('mysql');
var con = mysql.createConnection({
//data omitted
});
function AppendRecordset (req, res){
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
con.query(req, function (err, res) {
if (err) throw err;
console.log("1 record inserted");
});
});
}
function UpdateRecordset (req, res) {
con.connect(function(err) {
if (err) throw err;
con.query(req, function (err, res) {
if (err) throw err;
console.log(result.affectedRows + " record(s) updated");
});
});
}
function DeleteRecordset (req, res){
con.connect(function(err) {
if (err) throw err;
con.query(req, function (err, res) {
if (err) throw err;
console.log("Number of records deleted: " + result.affectedRows);
});
});
}
function GetRecordset (req, res) {
con.connect(function(err) {
if (err) throw err;
con.query(req, function (err, res, fields) {
if (err) throw err;
console.log(result);
});
});
}
}
I then have in a separate file(s) my app logic, and want to use what of the above as an object/class so I wrote this accordingly to that guide:
//##this is inside my main app file
//declare the sql processor
require('./mysql_test.js');
var DB = MySQL();
DB.AppendRecordset(sql_string, res); //sql_string contains a valid SQL statement
But when I try to acces it using `` I get this error message: ReferenceError: MySQL is not defined what am I doing wrong?
I think these functions handle your routes, so I didn't change them. Because I don't know how your router is desined.
Create a file dbHangler.js and write this single function:
const mysql = require('mysql');
let con;
exports.execQuery = (query) => {
return new Promise((resolve, reject) => {
if(!con) {
con = mysql.createConnection({
//data omitted
});
}
con.connect(function(err) {
if(err) {
reject(err);
}
else {
console.log("Connected!");
con.query(query, function (err, res) {
if (err) {
reject(err);
}
else {
resolve(res);
}
});
}
});
});
};
In your dedicated.js file, now you can write:
const dbObject = require('path/to/dbHandler');
function AppendRecordset (req, res){
dbObject.execQuery(req)
.then(result => {
console.log(result.affectedRows + " record(s) updated");
})
.catch(error => {
// handle error
});
}
function AppendRecordset (req, res){
dbObject.execQuery(req)
.then(result => {
console.log("Number of records deleted: " + result.affectedRows);
})
.catch(error => {
// handle error
});
}
function AppendRecordset (req, res){
dbObject.execQuery(req)
.then(result => {
console.log(result);
})
.catch(error => {
// handle error
});
}
UPDATE
I hope this one helps you.
DbHandler.js
const mysql = require('mysql');
class DbHandler {
constructor(config) {
let self = this;
self.dbConfig = config;
self.connection = mysql.createConnection({
//data omitted
});
}
queryExecuter(query) {
let self = this;
return new Promise((resolve, reject) => {
self.connection.connect(function (err) {
if (err) {
reject(err);
}
else {
console.log("Connected!");
self.connection.query(query, function (err, res) {
if (err) {
reject(err);
}
else {
resolve(res);
}
});
}
});
});
}
AppendRecordset(query) {
let self = this;
return self.queryExecuter(query)
.then(result => {
console.log("1 record inserted");
return result;
})
.catch(error => {
// handle error
throw error;
});
}
UpdateRecordset(query) {
let self = this;
return self.queryExecuter(query)
.then(result => {
console.log(result.affectedRows + " record(s) updated");
return result;
})
.catch(error => {
// handle error
throw error;
});
}
// and other functions
}
module.exports = DbHandler;
And use it like below:
let DB = require('/path/to/DbHandler');
let myDb = new DB(/* db config */);
db.UpdateRecordset('your query')
.then(res => {
console.log(res);
})
.catch(err => {
console.log(err);
});
I'm having issues with reading the data from a file created with fs.createWriteStream.
It looks like the stream.write get executed at the end of the program after the file is read as opposed to when they are called (which would explain why there is nothing in variable_3 at the time of outputting it).
The function used is as follow (simplified):
module.exports = async data1 => {
console.log('start');
try {
const stream = fs.createWriteStream(filename_1, { flags: "a" });
console.log('stream created');
stream.write("some data", (err) => {
if (err) {
console.log(err.message);
} else {
console.log("data written");
}
});
for (const variable_1 of object_1) {
const variable_2 = await function2({
// generates a buffer
});
stream.write(variable_2, (err) => {
if (err) {
console.log(err.message);
} else {
console.log("data written");
}
});
}
stream.end();
console.log('stream ended');
console.log('opening file');
const variable_3 = fs.readFileSync(filename_1);
console.log('file opened and read with data: ' + variable_3);
return;
} catch (error) {
console.log(error);
}
};
Output:
> start
> stream created
> stream ended
> opening file
> file opened and read with data:
> data written
> data written
Once the code has run however, when I open filename_1 (via the explorer), the whole data is present?!
Got it sorted in the end.
Didn't realise the stream functions don't return a promise so I had to manually return a promise.
Here is the code changed:
module.exports = async data1 => {
console.log('start');
try {
const stream = fs.createWriteStream(filename_1, { flags: "a" });
console.log('stream created');
stream.write("some data", (err) => {
if (err) {
console.log(err.message);
} else {
console.log("data written");
}
});
for (const variable_1 of object_1) {
const variable_2 = await function2({
// generates a buffer
});
stream.write(variable_2, (err) => {
if (err) {
console.log(err.message);
} else {
console.log("data written");
}
});
}
stream.end();
console.log('stream ended');
console.log('opening file');
const variable_3 = fs.readFileSync(filename_1);
console.log('file opened and read with data: ' + variable_3);
return new Promise(resolve => {
stream.on('finish', () => {
resolve('done');
console.log("createNRRD is done");
});
});
} catch (error) {
console.log(error);
}
};
I have three different sample.xml files which I have to convert into json output. I am trying to append all of their output into one json file. here is my code
const fs = require('fs');
const xml2js = require('xml2js');
parser = new xml2js.Parser({
explicitArray: true
})
fs.readFile('sample.xml', (err, data) => {
parser.parseString(data, (err, result) => {
let output = JSON.stringify(result.planes.plane);
fs.writeFile('output.json', output, 'utf8', (err) => {
if (err) {
throw err;
} else {
console.log('file created..')
}
})
});
});
now I know the function fs.appendfile() but I am not sure how do I do it? I have two more files named: sample2.xml and sample3.xml
this is what I have tried but the problem it is overwriting not appending.
const fs = require('fs');
const xml2js = require('xml2js');
const async = require('async');
parser = new xml2js.Parser({
explicitArray: true
})
let files = ['sample.xml', 'sample2.xml'];
async.map(files, fs.readFile, (err, files) => {
if (err) {
throw err;
} else {
files.forEach((file) => {
parser.parseString(file, (err, result) => {
let output = JSON.stringify(result.planes.plane);
fs.appendFile('output.json', output, 'utf8', (err) => {
if (err) {
throw err;
} else {
console.log('file created..')
}
})
});
})
}
})
You need to read each xml file, get the json-data from it, and then write it to the final file:
async.map(
files,
(file, cb) => {
fs.readFile(file, (err, data) => {
if (err) {
cb(err)
} else {
parser.parseString(data, (err, result) => {
cb(err, result.planes.plane)
})
}
})
},
function (err, results) {
if (err) {
throw err
} else {
let output = JSON.stringify(results)
fs.writeFile('output.json', output, 'utf8', (err) => {
if (err) {
throw err
} else {
console.log('file created...')
}
})
}
}
)
To catch errors I have written if-else blocks in every function which looks bad. Please suggest a better way to handle errors in async node
async.waterfall([
function(callback){
fnOne.GetOne(req, res,function(err,result) {
if(err){
console.error("Controller : fnOne",err);
callback(err,null);
}
else{
var fnOne = result;
callback(null, fnOne);
}
})
},
function(fnOne, callback){
fnTwo.two(fnOne,function(err,result) {
if(err) {
console.error(err);
callback(err,null);
}
else{
callback(null, context);
}
})
}
], function (err, result) {
if(err){
console.error("Controller waterfall Error" , err);
res.send("Error in serving request.");
}
});
You can pass the error to async and catch it in the callback
async.waterfall([
function (callback) {
fnOne.GetOne(req, res, callback); // err and result is passed in callback
}, // as it's "function(err, result)"
function (fnOne, callback) { // the same as the arguments for the
fnTwo.two(fnOne, callback); // callback function
}
], function (err, result) {
if (err) {
console.error("Error :", err);
res.send("Error in serving request.");
}else{
res.end("A-OK");
}
});
You do too much stuff
Waterfall already have an internal error management.
callback(err, [results]) - An optional callback to run once all the
functions have completed. This will be passed the results of the last
task's callback.
Try this
async.waterfall([
function(callback){
fnOne.GetOne(req,res, callback)
},
function(fnOne, callback){
fnTwo.two(fnOne,callback) {
}
], function (err, result) {
if(err){
console.error("Controller waterfall Error" , err);
res.send("Error in serving request.");
}
});
async.each(files, (file, callback) => {
// Create a new blob in the bucket and upload the file data.
const blob = bucket.file(file.file.originalname);
const blobStream = blob.createWriteStream();
blobStream.on('error', (err) => {
callback(err);
});
blobStream.on('finish', () => {
// The public URL can be used to directly access the file via HTTP.
Storage.bucket(BUCKET_NAME)
.file(blob.name)
.move(body.email + '_' + file.dir + '.' + blob.name.split('.').pop())
.then((e) => {
body[file.dir] = format(`https://storage.googleapis.com/${BUCKET_NAME}/${e[0].name}`)
callback();
})
.catch(err => {
console.error('ERROR: ', err);
});
});
blobStream.end(file.file.buffer);
}, (err) => {
if (err) {
console.error(err);
return res.status(422).send({error: true, data: {message: "An error occured. Please fill all fields and try again"}});
}
// save to db
});