晴明的博客园 GitHub      CodePen      CodeWars     

[node] node

 #

module.filename:开发期间,该行代码所在的文件。
__filename:始终等于 module.filename。
__dirname:开发期间,该行代码所在的目录。
process.cwd():运行node的工作目录,可以使用  cd /d 修改工作目录。
require.main.filename:用node命令启动的module的filename, 如 node xxx,这里的filename就是这个xxx。

require()方法的坐标路径是:module.filename;

fs.readFile()的坐标路径是:process.cwd()。

#

HTTP

 

http.createServer([requestListener])

Returns a new instance of http.Server.
The requestListener is a function which is automatically added to the 'request' event.

#

const http = require('http');

const server = http.createServer((req, res) => {
  res.end();
});
server.on('clientError', (err, socket) => {
  socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
});
server.listen(8000);

 

 

server.listen(handle[, callback])
server.listen(path[, callback])
server.listen(port[, hostname][, backlog][, callback])

 

 

response.setHeader(name, value)

Sets a single header value for implicit headers. If this header already exists in the to-be-sent headers, its value will be replaced. Use an array of strings here if you need to send multiple headers with the same name.

Example:
#

response.setHeader('Content-Type', 'text/html');


or
#

response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']);

Attempting to set a header field name or value that contains invalid characters will result in a TypeError being thrown.

 

 

response.writeHead(statusCode[, statusMessage][, headers])

Sends a response header to the request. The status code is a 3-digit HTTP status code, like 404. The last argument, headers, are the response headers. Optionally one can give a human-readable statusMessage as the second argument.

#

var body = 'hello world';
response.writeHead(200, {
  'Content-Length': Buffer.byteLength(body),
  'Content-Type': 'text/plain' });


This method must only be called once on a message and it must be called before response.end() is called.

If you call response.write() or response.end() before calling this, the implicit/mutable headers will be calculated and call this function for you.

When headers have been set with response.setHeader(), they will be merged with any headers passed to response.writeHead(), with the headers passed to response.writeHead() given precedence.

#

// returns content-type = text/plain
const server = http.createServer((req,res) => {
  res.setHeader('Content-Type', 'text/html');
  res.setHeader('X-Foo', 'bar');
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('ok');
});


Note that Content-Length is given in bytes not characters. The above example works because the string 'hello world' contains only single byte characters. If the body contains higher coded characters then Buffer.byteLength() should be used to determine the number of bytes in a given encoding. And Node.js does not check whether Content-Length and the length of the body which has been transmitted are equal or not.

Attempting to set a header field name or value that contains invalid characters will result in a TypeError being thrown.


response.getHeader(name)

Reads out a header that's already been queued but not sent to the client. Note that the name is case insensitive. This can only be called before headers get implicitly flushed.

Example:
#

var contentType = response.getHeader('content-type');



response.end([data][, encoding][, callback])

This method signals to the server that all of the response headers and body have been sent; that server should consider this message complete. The method, response.end(), MUST be called on each response.

If data is specified, it is equivalent to calling response.write(data, encoding) followed by response.end(callback).

If callback is specified, it will be called when the response stream is finished.

 

 

Process (进程)

 

process对象是一个全局对象,可以在任何地方访问到它。

 

process.env

一个包括用户环境的对象。

#

process.env.test = null;
console.log(process.env.test);
// => 'null'
process.env.test = undefined;
console.log(process.env.test);
// => 'undefined'


//Use delete to delete a property from process.env.
process.env.TEST = 1;
delete process.env.TEST;
console.log(process.env.TEST);
// => undefined

 


 

process.cwd()

#返回进程当前的工作目录。

console.log('当前目录:' + process.cwd());

 

 

process.argv

一个包含命令行参数的数组。第一个元素会是 'node', 第二个元素将是 .Js 文件的名称。接下来的元素依次是命令行传入的参数。

// 打印 process.argv
process.argv.forEach(function(val, index, array) {
  console.log(index + ': ' + val);
});

输出将会是:

$ node process-2.js one two=three four
0: node
1: /Users/mjr/work/node/process-2.js
2: one
3: two=three
4: four 

 

 

File System(文件系统)

文件系统模块是一个简单包装的标准 POSIX 文件 I/O 操作方法集。
可以通过调用require('fs')来获取该模块。
文件系统模块中的所有方法均有异步和同步版本。

文件系统模块中的异步方法需要一个完成时的回调函数作为最后一个传入形参。
回调函数的构成由调用的异步方法所决定,通常情况下回调函数的第一个形参为返回的错误信息。
如果异步操作执行正确并返回,该错误形参则为null或者undefined。

如果使用的是同步版本的操作方法,则一旦出现错误,会以通常的抛出错误的形式返回错误。
可以用try和catch等语句来拦截错误并使程序继续进行。

#

//异步版本的例子:

fs.unlink('/tmp/hello', function (err) {
  if (err) throw err;
  console.log('successfully deleted /tmp/hello');
});

//同步版本的例子:

fs.unlinkSync('/tmp/hello')
console.log('successfully deleted /tmp/hello');


#

//当使用异步版本时不能保证执行顺序,下面这个例子很容易出错:

fs.rename('/tmp/hello', '/tmp/world', function (err) {
  if (err) throw err;
  console.log('renamed complete');
});
fs.stat('/tmp/world', function (err, stats) {
  if (err) throw err;
  console.log('stats: ' + JSON.stringify(stats));
});

//fs.stat有可能在fs.rename前执行.要等到正确的执行顺序应该用下面的方法:

fs.rename('/tmp/hello', '/tmp/world', function (err) {
  if (err) throw err;
  fs.stat('/tmp/world', function (err, stats) {
    if (err) throw err;
    console.log('stats: ' + JSON.stringify(stats));
  });
});


在繁重的任务中,推荐使用这些函数的异步版本.
同步版本会阻塞进程,直到完成处理,也就是说会暂停所有的连接.

可以使用文件名的相对路径, 但是记住这个路径是相对于process.cwd()的.

大部分的文件系统(fs)函数可以忽略回调函数(callback)这个参数.
如果忽略它,将会由一个默认回调函数(callback)来重新抛出(rethrow)错误.
要获得原调用点的堆栈跟踪(trace)信息,需要在环境变量里设置NODE_DEBUG.

$ env NODE_DEBUG=fs node script.js
fs.js:66
        throw err;
              ^
Error: EISDIR, read
    at rethrow (fs.js:61:21)
    at maybeCallback (fs.js:79:42)
    at Object.fs.readFile (fs.js:153:18)
    at bad (/path/to/script.js:2:17)
    at Object.<anonymous> (/path/to/script.js:5:1)
    <etc.>

 


fs.readFile(file[, options], callback)


    file <String> | <Buffer> | <Integer> filename or file descriptor
    options <Object> | <String>
        encoding <String> | <Null> default = null
        flag <String> default = 'r'
    callback <Function>


#异步读取一个文件的全部内容。

fs.readFile('/etc/passwd', function (err, data) {
  if (err) throw err;
  console.log(data);
});


回调函数传递了两个参数 (err, data), data 就是文件的内容。
如果未指定编码方式,原生buffer就会被返回。   

 

#If options is a string, then it specifies the encoding.

fs.readFile('/etc/passwd', 'utf8', callback);

Any specified file descriptor has to support reading.     

Note: Specified file descriptors will not be closed automatically.

 

fs.readFileSync(file[, options])

    file <String> | <Buffer> | <Integer> filename or file descriptor
    options <Object> | <String>
        encoding <String> | <Null> default = null
        flag <String> default = 'r'

Synchronous version of fs.readFile. Returns the contents of the file.

If the encoding option is specified then this function returns a string.
Otherwise it returns a buffer.

 

fs.readdir(path[, options], callback)

    path <String> | <Buffer>
    options <String> | <Object>
        encoding <String> default = 'utf8'
    callback <Function>
 
读取 path 路径所在目录的内容。

 回调函数 (callback) 接受两个参数 (err, files)
 其中 files 是一个存储目录中所包含的文件名称的数组,
 数组中不包括 '.' 和 '..'。  

 

fs.ReadStream

ReadStream is a Readable Stream.

Event: 'open'
    fd <Integer> Integer file descriptor used by the ReadStream.

Emitted when the ReadStream's file is opened.

Event: 'close'

Emitted when the ReadStream's underlying file descriptor has been closed using the fs.close() method.

readStream.path
The path to the file the stream is reading from as specified in the first argument to fs.createReadStream(). If path is passed as a string, then readStream.path will be a string. If path is passed as a Buffer, then readStream.path will be a Buffer.


fs.createReadStream(path[, options])

    path <String> | <Buffer>
    
    options <String> | <Object>
        flags <String>
        encoding <String>
        fd <Integer>
        mode <Integer>
        autoClose <Boolean>
        start <Integer>
        end <Integer>
      

{
  flags: 'r',
  encoding: null,
  fd: null,
  mode: 0o666,
  autoClose: true
}


#一个从100字节的文件中读取最后10字节的例子:

fs.createReadStream('sample.txt', {start: 90, end: 99});

 

fs.createWriteStream(path[, options])

    path <String> | <Buffer>
    options <String> | <Object>
        flags <String>
        defaultEncoding <String>
        fd <Integer>
        mode <Integer>
        autoClose <Boolean>
        start <Integer>

Returns a new WriteStream object.

options is an object or string with the following defaults:

{
  flags: 'w',
  defaultEncoding: 'utf8',
  fd: null,
  mode: 0o666,
  autoClose: true
}

fs.Stats

Objects returned from fs.stat(), fs.lstat() and fs.fstat() and their synchronous counterparts are of this type.

    stats.isFile()
    stats.isDirectory()
    stats.isBlockDevice()
    stats.isCharacterDevice()
    stats.isSymbolicLink() (only valid with fs.lstat())
    stats.isFIFO()
    stats.isSocket()

For a regular file util.inspect(stats) would return a string very similar to this:

{
  dev: 2114,
  ino: 48064969,
  mode: 33188,
  nlink: 1,
  uid: 85,
  gid: 100,
  rdev: 0,
  size: 527,
  blksize: 4096,
  blocks: 8,
  atime: Mon, 10 Oct 2011 23:24:11 GMT,
  mtime: Mon, 10 Oct 2011 23:24:11 GMT,
  ctime: Mon, 10 Oct 2011 23:24:11 GMT,
  birthtime: Mon, 10 Oct 2011 23:24:11 GMT
}

Please note that atime, mtime, birthtime,
and ctime are instances of Date object and to compare the values of these objects you should use appropriate methods.
For most general uses getTime() will return the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC and this integer should be sufficient for any comparison,
however there are additional methods which can be used for displaying fuzzy information.

fs.stat(path, callback)

    path <String> | <Buffer>
    callback <Function>

The callback gets two arguments (err, stats) where stats is a fs.Stats object.

fs.statSync(path)

    path <String> | <Buffer>


Synchronous version of fs.stat().
Returns an instance of fs.Stats.

fs.access(path[, mode], callback)

    path <String> | <Buffer>
    mode <Integer>
    callback <Function>

Tests a user's permissions for the file or directory specified by path.
The mode argument is an optional integer that specifies the accessibility checks to be performed.
The following constants define the possible values of mode.
It is possible to create a mask consisting of the bitwise OR of two or more values.

    fs.constants.F_OK - path is visible to the calling process.
        This is useful for determining if a file exists,
        but says nothing about rwx permissions. Default if no mode is specified.
    fs.constants.R_OK - path can be read by the calling process.
    fs.constants.W_OK - path can be written by the calling process.
    fs.constants.X_OK - path can be executed by the calling process. This has no effect on Windows (will behave like fs.constants.F_OK).

The final argument, callback, is a callback function that is invoked with a possible error argument.
If any of the accessibility checks fail, the error argument will be populated.
The following example checks if the file /etc/passwd can be read and written by the current process.

fs.access('/etc/passwd', fs.constants.R_OK | fs.constants.W_OK, (err) => {
  console.log(err ? 'no access!' : 'can read/write');
});

fs.accessSync(path[, mode])

    path <String> | <Buffer>
    mode <Integer>

Synchronous version of fs.access().
This throws if any accessibility checks fail, and does nothing otherwise.

 

fs.mkdir(path[, mode], callback)

    path <String> | <Buffer>
    mode <Integer>
    callback <Function>

attempts to create a directory named pathname.

Asynchronous mkdir.
No arguments other than a possible exception are given to the completion callback.
mode defaults to 0o777.

fs.mkdirSync(path[, mode])

    path <String> | <Buffer>
    mode <Integer>

Synchronous mkdir.
Returns undefined.

fs.rmdir(path, callback)

    path <String> | <Buffer>
    callback <Function>

deletes a directory, which must be empty.

Asynchronous rmdir.
No arguments other than a possible exception are given to the completion callback.

fs.rmdirSync(path)

    path <String> | <Buffer>

Synchronous rmdir. Returns undefined.

fs.unlink(path, callback)

    path <String> | <Buffer>
    callback <Function>

delete a name and possibly the file it refers to
    
Asynchronous unlink.
No arguments other than a possible exception are given to the completion callback.

fs.unlinkSync(path)

    path <String> | <Buffer>

Synchronous unlink.
Returns undefined.

fs.exists (Deprecated)
fs.existsSync (Deprecated)



Stream(流)

 

流是一个抽象接口,被 Node 中的很多对象所实现。
比如对一个 HTTP 服务器的请求是一个流,stdout 也是一个流。
流是可读、可写或兼具两者的。
所有流都是 EventEmitter 的实例。

可以通过 require('stream') 加载 Stream 基类,
其中包括了 Readable 流、Writable 流、Duplex 流和 Transform 流的基类。

#

const http = require('http');

var server = http.createServer( (req, res) => {
  // req is an http.IncomingMessage, which is a Readable Stream
  // res is an http.ServerResponse, which is a Writable Stream

  var body = '';
  // we want to get the data as utf8 strings
  // If you don't set an encoding, then you'll get Buffer objects
  req.setEncoding('utf8');

  // Readable streams emit 'data' events once a listener is added
  req.on('data', (chunk) => {
    body += chunk;
  });

  // the end event tells you that you have entire body
  req.on('end', () => {
    try {
      var data = JSON.parse(body);
    } catch (er) {
      // uh oh!  bad json!
      res.statusCode = 400;
      return res.end(`error: ${er.message}`);
    }

    // write back something interesting to the user:
    res.write(typeof data);
    res.end();
  });
});

server.listen(1337);

// $ curl localhost:1337 -d '{}'
// object
// $ curl localhost:1337 -d '"foo"'
// string
// $ curl localhost:1337 -d 'not json'
// error: Unexpected token o

 

readable.pipe(destination[, options])


    destination <stream.Writable> The destination for writing data
    options <Object> Pipe options
        end <Boolean> End the writer when the reader ends. Defaults to true.

The readable.pipe() method attaches a Writable stream to the readable, causing it to switch automatically into flowing mode and push all of its data to the attached Writable. The flow of data will be automatically managed so that the destination Writable stream is not overwhelmed by a faster Readable stream.

The following example pipes all of the data from the readable into a file named file.txt:

const readable = getReadableStreamSomehow();
const writable = fs.createWriteStream('file.txt');
// All the data from readable goes into 'file.txt'
readable.pipe(writable);

 



It is possible to attach multiple Writable streams to a single Readable stream.

The readable.pipe() method returns a reference to the destination stream making it possible to set up chains of piped streams:

const r = fs.createReadStream('file.txt');
const z = zlib.createGzip();
const w = fs.createWriteStream('file.txt.gz');
r.pipe(z).pipe(w);

 



By default, stream.end() is called on the destination Writable stream when the source Readable stream emits 'end', so that the destination is no longer writable. To disable this default behavior, the end option can be passed as false, causing the destination stream to remain open, as illustrated in the following example:

reader.pipe(writer, { end: false });
reader.on('end', () => {
  writer.end('Goodbye\n');
});


One important caveat is that if the Readable stream emits an error during processing, the Writable destination is not closed automatically. If an error occurs, it will be necessary to manually close each stream in order to prevent memory leaks.

Note: The process.stderr and process.stdout Writable streams are never closed until the Node.js process exits, regardless of the specified options.


Path (路径)

require('path')

 

path.join([path1], [path2], [...])

连接所有参数, 并且规范化得到的路径
参数必须是字符串

Note: If the arguments to join have zero-length strings,
unlike other path module functions, they will be ignored.
If the joined path string is a zero-length string then '.' will be returned,
which represents the current working directory.

#

path.join('/foo', 'bar', 'baz/asdf', 'quux', '..')
// returns '/foo/bar/baz/asdf'

path.join('foo', {}, 'bar')
// throws exception
TypeError: Arguments to path.join must be strings

 

 


path.extname(path)

返回路径中文件的扩展名, 在从最后一部分中的最后一个'.'到字符串的末尾。
如果在路径的最后一部分没有'.',或者第一个字符是'.',就返回一个 空字符串。
#

path.extname('index.html')
// returns '.html'

path.extname('index.coffee.md')
// returns '.md'

path.extname('index.')
// returns '.'

path.extname('index')
// returns ''

path.extname('.index')
// returns ''

 

path.dirname(path)

返回路径中文件夹的名称. 类似于Unix的dirname 命令.

#

path.dirname('/foo/bar/baz/asdf/quux')
// returns '/foo/bar/baz/asdf'

 

path.basename(path[, ext])
   

 path <String>
   ext <String> An optional file extension

The path.basename() methods returns the last portion of a path, similar to the Unix basename command.

For example:

path.basename('/foo/bar/baz/asdf/quux.html')
  // returns 'quux.html'

path.basename('/foo/bar/baz/asdf/quux.html', '.html')
  // returns 'quux'


A TypeError is thrown if path is not a string or if ext is given and is not a string.

 

path.resolve([path[, ...]])

    [path[, ...]] <String> A sequence of paths or path segments

The path.resolve() method resolves a sequence of paths or path segments into an absolute path.

The given sequence of paths is processed from right to left,
with each subsequent path prepended until an absolute path is constructed.
For instance, given the sequence of path segments: /foo, /bar, baz,
calling path.resolve('/foo', '/bar', 'baz') would return /bar/baz.

If after processing all given path segments an absolute path has not yet been generated,
the current working directory is used.

The resulting path is normalized and trailing slashes are removed unless the path is resolved to the root directory.

Zero-length path segments are ignored.

If no path segments are passed,
path.resolve() will return the absolute path of the current working directory.

For example:

path.resolve('/foo/bar', './baz')
// returns '/foo/bar/baz'

path.resolve('/foo/bar', '/tmp/file/')
// returns '/tmp/file'

path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif')
// if the current working directory is /home/myself/node,
// this returns '/home/myself/node/wwwroot/static_files/gif/image.gif'

A TypeError is thrown if any of the arguments is not a string.

 

##path.normalize(path)
```
    path <String>
```
The path.normalize() method normalizes the given path,
resolving '..' and '.' segments.

When multiple, sequential path segment separation characters are found (e.g. / on POSIX and \ on Windows),
they are replaced by a single instance of the platform specific path segment separator.
Trailing separators are preserved.

If the path is a zero-length string, '.' is returned, representing the current working directory.

For example on POSIX:
```
path.normalize('/foo/bar//baz/asdf/quux/..')
// returns '/foo/bar/baz/asdf'
```
On Windows:
```
path.normalize('C:\\temp\\\\foo\\bar\\..\\');
// returns 'C:\\temp\\foo\\'
```
A TypeError is thrown if path is not a string.

##path.sep
Provides the platform-specific path segment separator:
```
    \ on Windows
    / on POSIX
```
For example on POSIX:
```
'foo/bar/baz'.split(path.sep)
// returns ['foo', 'bar', 'baz']
```
On Windows:
```
'foo\\bar\\baz'.split(path.sep)
// returns ['foo', 'bar', 'baz']
```

 

OS(操作系统)

提供一些基本的操作系统相关函数。
使用 require('os')


os.EOL

一个定义了操作系统的一行结束的标识的常量。

 

os.tmpdir()

返回操作系统默认的临时文件目录

 

##os.platform()

The os.platform() method returns a string identifying the operating system platform as set during compile time of Node.js.

Currently possible values are:
```
    'aix'
    'darwin'
    'freebsd'
    'linux'
    'openbsd'
    'sunos'
    'win32'
```
Equivalent to process.platform.

Note: The value 'android' may also be returned if the Node.js is built on the Android operating system.
However, Android support in Node.js is considered to be experimental at this time.

##os.type()

The os.type() method returns a string identifying the operating system name as returned by uname. For example 'Linux' on Linux, 'Darwin' on OS X and 'Windows_NT' on Windows.





 

util(工具)

使用模块 'util'中已定义的方法.
require('util')

 

util.isRegExp(object)#Stability: 0 - Deprecated

用 Object.prototype.toString.call(object)=='[object RegExp]' 替代

 

Query String 

const querystring = require('querystring');


querystring.escape(str)

The querystring.escape() method performs URL percent-encoding on the given str in a manner that is optimized for the specific requirements of URL query strings.

The querystring.escape() method is used by querystring.stringify() and is generally not expected to be used directly.
It is exported primarily to allow application code to provide a replacement percent-encoding implementation if necessary by assigning querystring.escape to an alternative function.



querystring.parse(str[, sep[, eq[, options]]])

The querystring.parse() method parses a URL query string (str) into a collection of key and value pairs.

For example, the query string 'foo=bar&abc=xyz&abc=123' is parsed into:

{
  foo: 'bar',
  abc: ['xyz', '123']
}


querystring.parse('foo=bar&baz=qux&baz=quux&corge')
// returns
{ foo: 'bar', baz: ['qux', 'quux'], corge: '' }

querystring.stringify(obj[, sep[, eq[, options]]])

The querystring.stringify() method produces a URL query string from a given obj by iterating through the object's "own properties".

For example:

querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' })
// returns 'foo=bar&baz=qux&baz=quux&corge='

querystring.stringify({foo: 'bar', baz: 'qux'}, ';', ':')
// returns 'foo:bar;baz:qux'

querystring.unescape(str)

The querystring.unescape() method performs decoding of URL percent-encoded characters on the given str.
The querystring.unescape() method is used by querystring.parse() and is generally not expected to be used directly.
It is exported primarily to allow application code to provide a replacement decoding implementation if necessary by assigning querystring.unescape to an alternative function.

 

#process

##process.platform

The process.platform property returns a string identifying the operating system platform on which the Node.js process is running.
For instance 'darwin', 'freebsd', 'linux', 'sunos' or 'win32'
```
console.log(`This platform is ${process.platform}`);
```

posted @ 2016-06-03 19:20  晴明桑  阅读(305)  评论(0编辑  收藏  举报