Begin accepting connections on the specified port and hostname. If the hostname is omitted, the server will accept connections on any IPv6 address (::) when IPv6 is available, or any IPv4 address (0.0.0.0) otherwise. A port value of zero will assign a random port.
So, the following code would print running at http://:::3456:
var express = require('express');
var app = express();
var server = app.listen(3456, function () {
var host = server.address().address;
var port = server.address().port;
console.log('running at http://' + host + ':' + port)
});
But if you add an explicit hostname:
var server = app.listen(3456, "127.0.0.1", function () {
It would print what you want to see: running at http://127.0.0.1:3456
Also you might want to use some IP lib as pointed in this answer
821Node.js Express 框架
该语句执行后,如果保存路径存在中文字符,直接输出会产生保存路径中文部分乱码的问题,需要在此语句之前声明头,后可正常输出中文字符:
res.writeHead(200,{'Content-Type':'text/html;charset=utf-8'}); res.end( JSON.stringify( response ) );820Node.js Express 框架
server.address().address 会返回 : 的问题,查证相关文档
As the docs say,
So, the following code would print running at http://:::3456:
var express = require('express'); var app = express(); var server = app.listen(3456, function () { var host = server.address().address; var port = server.address().port; console.log('running at http://' + host + ':' + port) });But if you add an explicit hostname:
var server = app.listen(3456, "127.0.0.1", function () {It would print what you want to see: running at http://127.0.0.1:3456
Also you might want to use some IP lib as pointed in this answer
也就是说默认为 IPV6 模式了,至于如何改可能要研究下,所以地址最好显示声明为 "127.0.0.1" 或 localhost。819Node.js 文件系统
回复上一楼。文件夹不必一层一层创建的,上面的教程其实写了。
可以添加 recursive: true 参数,不管创建的目录 tmp 是否存在:
var fs = require("fs"); fs.mkdir('tmp/test', { recursive: true }, (err) => { if (err) throw err; console.log("Finish."); });818Node.js 文件系统
mkdir 方法创建目录小坑:
比如在当前目录下创建目录 /tmp/test/,过程如下:
开始我这样写的:
console.log("创建目录 //test/"); fs.mkdir("./tmp/test/",function(err){ if (err) { return console.error(err); } console.log("目录创建成功。"); });然后运行抛出异常(no such file or directory,mkdir...)如下:
后来发现目录要一层一层创建,修改后代码如下:
console.log("创建目录 /tmp/test/"); //异步 fs.mkdir("./tmp/",function(err){ if (err) { return console.error(err); } console.log("tmp目录创建成功。"); fs.mkdir("./tmp/test/",function(err){ if (err) { return console.error(err); } console.log("test目录创建成功。"); }); }); console.log("创建目录 /tmp1/test/"); //同步 fs.mkdirSync("./tmp1/"); fs.mkdirSync("./tmp1/test/");817Node.js 文件系统
fs.writeFile 并不一定是覆盖原来文件内容,而是取决于打开文件时带的 flags。如果是通过 writeFile 直接打开文件默认是 w 模式,但是也可以通过 open 打开文件指定模式,然后通过 writeFile 来写文件,比如:
fs.open(fileName, "a+", function(err, fd){ if (err) { return console.error(err); } fs.writeFile(fd, "bb", function(err){ if (err){ return console.error(err); } }); });上面的 writeFile 是追加模式写文件。