在导出的模块中节点jscallback

我是一个节点新手,所以如果这是简单的原谅我。

我正在尝试一个函数完成后运行一个callback。 不pipe我在哪边尝试,callback都会先执行。

我的模块import_data.js

module.exports.download = function(url, path, supplier, callback) { //SF add dates to logging console.log('Import for '+supplier+' started'); request({uri: url}) .pipe(fs.createWriteStream(path)) .on('close', function() { console.log('Import complete'); },function(err, data){ callback; }); }; 

import_js被调用通用

 'use strict'; //var db = require('../config/sequelize').sequelize; var common = require('./common/index.js'), async = require('async'); common.importData( 'www.url.com', '/tmp/target.csv', 'Target Compenents', console.log('callback') ); 

我希望console.log('calback')是最后logging的事情。

任何帮助不胜感激。

你必须添加一个函数作为你的callback, console.log它只是方法,它不是一个函数,你可以用它作为callback。
所以要修复它,你可以把你的console.log包装到如下所示的函数中:

 common.importData( 'www.url.com', '/tmp/target.csv', 'Target Compenents', function(){console.log('callback')} ); 

我希望这会帮助你,谢谢!

它应该是这样的:

 module.exports.download = function(url, path, supplier, callback) { //SF add dates to logging console.log('Import for '+supplier+' started'); request({uri: url}) .pipe(fs.createWriteStream(path)) .on('response', function(response) { // now it's ready callback(response); }) .on('error', function(err) { console.log(err); }); }; 

应用

 common.download('some_url', 'target.csv', 'Target Components', function(response) { console.info(response); // .... });