[编辑]
我明白了。代码最终如下:
$filepath="/Users/me/Desktop/text.txt"
'test text 123' |Out-File -Path $filepath
(Get-Content $filepath|Out-String).Replace('test','1').Replace('text','2').Replace('123','3')|Set-Content $filepath
Get-Content $filepath
1 2 3
和
//getTrelloJSON.js
var request = require('request');
'use strict';
function getProjJSON(requestURL, callback){
request.get({
url: requestURL,
json: true,
headers: {'User-Agent': 'request'}
}, (err, res, data) => {
if (err) {
console.log('Error:', err);
} else if (res.statusCode !== 200) {
console.log('Status:', res.statusCode);
} else {
callback(data);
}
});
}
module.exports.getProjJSON = getProjJSON;
我运行//showData.js
var getJSON = require('./getTrelloJSON');
getJSON.getProjJSON('https://trello.com/b/saDpzgbw/ld40-gem-sorceress.json', (result) => {
var lists = result.lists;
console.log(lists);
});
并获取json然后我可以根据需要操作它。我打印只是为了表明它有效。
[编辑结束]
我是node.js的新手,我正面临一个菜鸟问题。 这段代码应该从公共trello板请求一个JSON并返回一个带有trello的json(列表部分)部分的对象。
第一个node showData.js
不起作用,但第二个{。}}。
如何在打印之前等待console.log()
完成?
getProjJSON()
答案 0 :(得分:0)
Node.js就是回调。 在这里,您只需注册数据回调。
var client = require('http');
var options = {
hostname: 'host.tld',
path: '/{uri}',
method: 'GET', //POST,PUT,DELETE etc
port: 80,
headers: {} //
};
//handle request;
pRequest = client.request(options, function(response){
console.log("Code: "+response.statusCode+ "\n Headers: "+response.headers);
response.on('data', function (chunk) {
console.log(chunk);
});
response.on('end',function(){
console.log("\nResponse ended\n");
});
response.on('error', function(err){
console.log("Error Occurred: "+err.message);
});
});
或者这是一个完整的例子,希望这能解决你的问题
const postData = querystring.stringify({
'msg' : 'Hello World!'
});
const options = {
hostname: 'www.google.com',
port: 80,
path: '/upload',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(postData)
}
};
const req = http.request(options, (res) => {
console.log(`res_code: ${res.statusCode}`);
console.log(`res_header: ${JSON.stringify(res.headers)}`);
res.setEncoding('utf8');
res.on('data', (chunk) => {
console.log(`res_data: ${chunk}`);
});
res.on('end', () => {
console.log('end of response');
});
});
req.on('error', (e) => {
console.error(`response error ${e.message}`);
});
//write back
req.write(postData);
req.end();