I actually want to put the "read" function in a different module and then require it in my main app.js. (I'm quite new to using promises)
[REVISED]
var dir = require('node-dir');
var files = function getFiles(){
return new Promise(function (resolve, reject) {
dir.files('../sample/sample', function (err, res){
if (err) {
reject(err);
console.log('Oops, an error occured %s', err);
}
else {
resolve(res);
return res;
}
});
});
}
console.log(files);
module.exports = files;
UPDATE AGAIN:
//read.js
var dir = require('node-dir');
var Promise = require('promise');
module.exports = new Promise(function (resolve, reject) {
dir.files('../sample/sample', function (error, results){
if (error) {
reject(error);
console.log('Oops, an error occured %s', err);
}
else {
resolve(results);
}
});
})
//app.js
var filelist = require('./read');
filelist.then(function (res){
console.log(res);
})
How do I go about that? I've tried "return new promise..." and putting the whole thing in a getFile function, but it doesn't return anything.
What am I doing wrong?
Every module can have two different types of export, named export and default export. You can have multiple named exports per module but only one default export.
Exporting values with just the exports keyword is a quick way to export values from a module. You can use this keyword at the top or bottom, and all it does is populate the module. exports object. But if you're using exports in a file, stick to using it throughout that file.
module. Exports is the object that is returned to the require() call. By module. exports, we can export functions, objects, and their references from one file and can use them in other files by importing them by require() method.
Default Exports: Default exports are useful to export only a single object, function, variable. During the import, we can use any name to import.
var dir = require('node-dir');
var files = new Promise(function (resolve, reject) {
dir.files('../sample/sample.txt', function (err, res){
if (err) {
reject(err);
console.log('Oops, an error occured %s', err);
}
else {
resolve(res);
}
});
});
exports.files = files;
And then use it as such on the file that imports this module.
var read = require('read.js');
read.files.then(function(res) {
console.log(res);
});
var dir = require('node-dir');
var files = function(){
return new Promise(function (resolve, reject) {
dir.files('../sample/sample', function (err, res){
if (err) {
reject(err);
console.log('Oops, an error occured %s', err);
}
else {
resolve(res);
return res;
}
});
});
}
exports.files = files;
var read = require('read.js');
read.files().then(function(res) {
console.log(res);
});
Hope that helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With