I have created a file called config.js which looks like below:
const config = {
staticFiles:{
name:[
'./',
'./index.html',
'./script.js',
'./icon.jpg'
]
},
outputFolderName: "D:\\DemoApp",
sourceApplicationParentPath: "D:\\DemoApp\\"
};
Now I am reading list of files from sourceApplicationParentPath folder using node and have to update staticFiles array of above file. I am not sure how should I do it. Can someone please help.
Thanks in advance.
config.js
const config = {
staticFiles: {
name: ['./',
'./index.html',
'./script.js',
'./icon.jpg',
]
},
outputFolderName: 'D:\\DemoApp',
sourceApplicationParentPath: 'D:\\DemoApp'
};
module.exports = config;
index.js
var fs = require('fs'),
config = require('./config'),
util = require('util');
fs.readdir(config.sourceApplicationParentPath, function(err, files) {
if (err) console.log(err.message);
for (var i = 0; i < files.length; i++) {
if (config.staticFiles.name.indexOf(`./${files[i]}`) == -1) {
config.staticFiles.name.push('./' + files[i]);
}
if (i == (files.length - 1)) {
var buffer = `const config = \n ${util.inspect(config, false, 2, false)}; \n module.exports = config;`;
fs.writeFile('./config.js', buffer, function(err) {
err || console.log('Data replaced \n');
})
}
}
});
The Above code is tested and working fine.
You can add or change the object or an array or value in config.js without duplicate entry.
config.js
const config = {
staticFiles:{
name:[
'./',
'./index.html',
'./script.js',
'./icon.jpg'
]
},
outputFolderName: "D:\\DemoApp",
sourceApplicationParentPath: "D:\\DemoApp\\"
};
exports.config = config;
code for the file from where you want to change the data
var fs = require('fs');
var bodyparser = require('body-parser');
var config = require('./config.js')
//path of directory
var directoryPath = "D:\\DemoApp\\"
var data = config.config;
//passsing directoryPath and callback function
fs.readdir(directoryPath, function (err, files) {
//handling error
if (err) {
return console.log('Unable to scan directory: ' + err);
}
var dataToUpdate = data.staticFiles.name;
//listing all files using forEach
files.forEach(function (file) {
// Do whatever you want to do with the file
console.log(file)
dataToUpdate.push(file)
});
data.staticFiles.name = dataToUpdate;
var value = 'const config = ' + JSON.stringify(data) + ';' + '\n' + 'exports.config = config';
fs.writeFile('./config.js',value, er => {
if(er){
throw er;
}
else{console.log('success')}
});
});
I'm using module.exports to export list of module. Below is my
Models/Message.js
var msgModel = function()
{
var getMsg = function() {
return "Hello World";
}
return{
getMsg : getMsg
}
}
module.exports = msgModel;
Below is my app.js
var msgModel = require('./Models/Message');
console.log(msgModel.getMsg());
It raised me error
console.log(msgModel.getMsg());
^
I can't figure out the problem.
You need to do console.log(msgModel().getMsg());. This is because msgModel is a function. I would suggest rewriting your msgModel like the example below instead to achieve the call you wanted.
var msgModel = {
getMsg: function() {
return "Hello World";
}
};
module.exports = msgModel;
You could do something like this:
var msg = new msgModel();
console.log(msg.getMsg());
You should export a function and invoke it in the main app.js
for example:
app.js
var msgModel = require('./Models/Message');
msgModel();
Message.js
var getMsg = function(){
console.log("Hello World!");
};
module.exports = getMsg;
You could write it this way in order to group more functions:
module.exports = {
getMsg: function() {
return "Hello World";
},
anotherFnc: function () {
...
}
};
then you could use:
var msgModel = require('./Models/Message');
console.log(msgModel.getMsg());
I have a problem with object attributes in Node.js. While attributes are set as expected in the test object, the same doesn't work for my articles object. The difference I see is that the functions of articles are called asynchronously. I must confess that I am a bit lost...
Here is app.js, that instantiates the test object and the articles object.
/**
* Load express.
*/
var express = require('express');
var app = express();
/**
* Load articles.
*/
var articles = require('./article.js');
var l_articles = new articles.Articles();
var test = require('./test.js');
var l_test = new test.Test();
app.get('/', function (req, res) {
console.log(l_test.get());
l_test.set('it is', 'midnight');
console.log(l_test.get());
articles.Articles.get(1);
res.send('OK');
})
app.listen(3001, function () {
console.log(l_test.get());
l_test.set('goodbye', 'sunshine');
console.log(l_test.get());
})
Here is my fairly simple test.js :
var app = require('./app.js');
function Test() {
this.timestamp = new Date();
console.log(this.timestamp);
this.attribute1 = 'hello';
this.attribute2 = 'world';
}
Test.prototype.get = function() {
console.log(this.timestamp);
return (this.attribute1 + ' ' + this.attribute2);
}
Test.prototype.set = function(p_param1, p_param2) {
console.log(this.timestamp);
this.attribute1 = p_param1;
this.attribute2 = p_param2;
}
module.exports = {
Test: Test
};
Here is my fairly simple article.js :
var sqlite3 = require('sqlite3').verbose();
var app = require('./app.js');
function Articles(p_id) {
this.timestamp = new Date();
console.log(this.timestamp);
this.db = new sqlite3.Database('./gescom.sqlite');
if (p_id == undefined) {
this.db.all('SELECT * FROM T_ARTICLE', this.load);
} else {
this.db.all('SELECT * FROM T_ARTICLE WHERE id = ' & p_id, this.load);
}
}
Articles.prototype.load = function(p_err, p_rows) {
console.log(this.timestamp);
var ids = [];
var articles = [];
p_rows.forEach(function(p_row) {
ids.push(p_row.ID);
articles.push([p_row.ID, p_row.SHORT_NAME]);
});
this.ids = ids;
this.articles = articles;
console.log(this.ids.length + ' articles loaded from database.');
}
Articles.prototype.get = function (p_id) {
console.log(this.timestamp);
var l_return;
if ((this.ids == undefined) || (this.articles == undefined)) {
console.log('No articles loaded from database.');
} else {
console.log(this.ids.length + ' articles loaded from database.');
if (p_id == undefined) {
l_return = this.articles;
} else {
if (this.ids.indexOf(p_id) != undefined) {
l_return = (this.articles[this.ids.indexOf(p_id)]);
} else {
l_return = undefined;
}
}
}
return l_return;
}
module.exports = {
Articles: Articles
};
how to call methods with variable in node.js
this is so that ;
var file=require("./file");
var method=b;
file.method();
//output
//error : TypeError: file.method is not a function
how to use it?
ok try this then
//file.js
module.exports = {
index: function () {
console.log("index called");
},
index2 :function() {
console.log("index2 called");
} ,
index3 : function () {
console.log("index3 called");
}
};
then
app.get("file/:method",function (req,res)
{
var method = req.params.name;
var file = require('./file');
file[method]();
}
app.get("file/:method",function (req,res)
{
var file("./file");
var method=req.params.name;
file.method();
this is what ı want to tell
I am trying to transition from async to promises and this is what I have. If the code looks contrived it's because I simplified it from what I'm working on to make it easier to grasp. I'm struggling to get the Promise.all to execute.
I commented out the async code that I want to implement in promises:
var Promise = require('bluebird');
var fs = Promise.promisifyAll(require('fs-extra'));
var path = require('path');
var tar = require('tar-fs');
module.exports = Archive;
function Archive() {
var self = this;
var self.base_dir = '/bar/baz',
var self.file1 = 'foo/file1',
var self.file2 = 'foo/file2',
var self.file3 = 'foo/file3',
var self.file4 = 'foo/file4'
}
Archive.prototype.make = function(done) {
var self = this;
// async.series([
// function(next) {
// self._prepareFilesDir(next);
// },
// function(next) {
// self._copyFiles(next);
// },
// function(next) {
// self._writeArchive(next);
// }
// ], done)
self._prepareFilesDir().bind(self)
.then(self._copyFiles.bind(self))
.then(self._writeArchive.bind(self))
.catch(function(e) {
return done(e);
});
};
// ********************************
// * Private functions
// ********************************
Archive.prototype._prepareFilesDir = function() {
var self = this;
return fs.emptyDirAsync(self.base_dir);
};
Archive.prototype._copyFiles = function() {
var self = this;
var sources = {
file1: path.resolve('baz', 'file1'),
file2: path.resolve('baz', 'file2')
file3: path.resolve('baz', 'file3')
file4: path.resolve('baz', 'file4')
file5: path.resolve('baz', 'file5')
};
var destinations = {
file1: path.resolve(self.base_dir, self.file1),
file2: path.resolve(self.base_dir, self.file2),
file3: path.resolve(self.base_dir, self.file3),
file4: path.resolve(self.base_dir, self.file4),
file5: path.resolve(self.base_dir, self.file5)
};
var filters = {
qux: /^qux/,
bru: /^bru/,
blerg: /blerg$/
};
function copyFile1() {
console.log('hello world');
return fs.copyAsync(sources.file2, destinations.file1, { filter: filters.qux });
};
function copyFile2() {
return fs.copyAsync(sources.file2, destinations.file2);
};
function copyFile3() {
return fs.copyAsync(sources.file3, destinations.file3, { filter: filters.bru });
};
function copyFile4() {
return fs.copyAsync(sources.file4, destinations.file4, { filter: filters.blerg });
};
return Promise.all([
copyFile1,
copyFile2,
copyFile3,
copyFile4
]);
// async.parallel([
// copyFile1(next),
// copyFile2(next),
// copyFile3(next),
// copyFile4(next)
// ], function(err) {
// if (err) return done(err);
// done(null);
// })
};
Archive.prototype._writeArchive = function() {
var self = this;
var archive_dir_path = path.resolve(self.base_dir, '..');
var tarPromise = function() {
return new Promise(function(resolve, reject) {
tar.pack(self.files_path)
.pipe(fs.createWriteStream(archive_dir_path + '.tar'))
.on('error', reject)
.on('finish', resolve)
});
};
fs.ensureDirAsync(archive_dir_path)
.then(tarPromise);
};
I must be doing something wrong because the 'hello world' is never printed. I think the stream is promisified correctly but I'm not so sure either. I based my conversion on the promise-nuggets.github.io snippets.
How do I have to do the Promise.all? I'd like to keep separate functions as I think it helps understanding the code better.
Thanks,
the mistakes that I found:
in make method, done would be called only in case of error, suggestion remove done callback, just return promise
again in make, you are doing _prepareFilesDir().bind(self), for staters bind at that point is redundant, it should have been call/apply at that point.
in _writeArchive, you need to return promise, else it ll return undefined and assume that the async function is finished.
updated code in fiddle
There were several issues which #mido22 fixed. There is one more issue though, in Pormise.all(), the functions shouldn't be passed as references but rather executed.
var Promise = require('bluebird');
var fs = Promise.promisifyAll(require('fs-extra'));
var path = require('path');
var tar = require('tar-fs');
module.exports = Archive;
function Archive() {
var self = this;
var self.base_dir = '/bar/baz',
var self.file1 = 'foo/file1',
var self.file2 = 'foo/file2',
var self.file3 = 'foo/file3',
var self.file4 = 'foo/file4'
}
Archive.prototype.make = function() { // CHANGED
var self = this;
// async.series([
// function(next) {
// self._prepareFilesDir(next);
// },
// function(next) {
// self._copyFiles(next);
// },
// function(next) {
// self._writeArchive(next);
// }
// ], done)
return self._prepareFilesDir() // CHANGED
.then(self._copyFiles.bind(self))
.then(self._writeArchive.bind(self)); // CHANGED
};
// ********************************
// * Private functions
// ********************************
Archive.prototype._prepareFilesDir = function() {
var self = this;
return fs.emptyDirAsync(self.base_dir);
};
Archive.prototype._copyFiles = function() {
var self = this;
var sources = {
file1: path.resolve('baz', 'file1'),
file2: path.resolve('baz', 'file2')
file3: path.resolve('baz', 'file3')
file4: path.resolve('baz', 'file4')
file5: path.resolve('baz', 'file5')
};
var destinations = {
file1: path.resolve(self.base_dir, self.file1),
file2: path.resolve(self.base_dir, self.file2),
file3: path.resolve(self.base_dir, self.file3),
file4: path.resolve(self.base_dir, self.file4),
file5: path.resolve(self.base_dir, self.file5)
};
var filters = {
qux: /^qux/,
bru: /^bru/,
blerg: /blerg$/
};
function copyFile1() {
console.log('hello world');
return fs.copyAsync(sources.file2, destinations.file1, { filter: filters.qux });
};
function copyFile2() {
return fs.copyAsync(sources.file2, destinations.file2);
};
function copyFile3() {
return fs.copyAsync(sources.file3, destinations.file3, { filter: filters.bru });
};
function copyFile4() {
return fs.copyAsync(sources.file4, destinations.file4, { filter: filters.blerg });
};
return Promise.all([
copyFile1(), // execute functions
copyFile2(), // idem
copyFile3(), // idem
copyFile4() // idem
]);
// async.parallel([
// copyFile1(next),
// copyFile2(next),
// copyFile3(next),
// copyFile4(next)
// ], function(err) {
// if (err) return done(err);
// done(null);
// })
};
Archive.prototype._writeArchive = function() {
var self = this;
var archive_dir_path = path.resolve(self.base_dir, '..');
var tarPromise = function() {
return new Promise(function(resolve, reject) {
tar.pack(self.files_path)
.pipe(fs.createWriteStream(archive_dir_path + '.tar'))
.on('error', reject)
.on('finish', resolve)
});
};
return fs.ensureDirAsync(archive_dir_path)
.then(tarPromise); // CHANGED,
};